c/c++语言利用socket编程获取网络上天气预报全部代码
时间: 2023-12-13 16:04:01 浏览: 165
C++获取天气信息
4星 · 用户满意度95%
以下是一个简单的示例,演示了如何使用C++和socket编程从网站获取天气预报数据:
```c++
#include <iostream>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
struct addrinfo hints, *res, *p;
int sockfd;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (argc != 2) {
std::cerr << "Usage: weatherforecast hostname" << std::endl;
return 1;
}
int status = getaddrinfo(argv[1], "80", &hints, &res);
if (status != 0) {
std::cerr << "getaddrinfo error: " << gai_strerror(status) << std::endl;
return 2;
}
for (p = res; p != NULL; p = p->ai_next) {
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sockfd == -1) {
std::cerr << "socket error" << std::endl;
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
std::cerr << "connect error" << std::endl;
continue;
}
break;
}
if (p == NULL) {
std::cerr << "failed to connect" << std::endl;
return 3;
}
freeaddrinfo(res);
const char *request = "GET / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n";
char buffer[1024];
sprintf(buffer, request, argv[1]);
send(sockfd, buffer, strlen(buffer), 0);
int bytes_received;
while ((bytes_received = recv(sockfd, buffer, 1024, 0)) > 0) {
buffer[bytes_received] = '\0';
std::cout << buffer;
}
close(sockfd);
return 0;
}
```
以上代码可以连接到指定的主机并发送HTTP GET请求,并将响应打印到控制台上。你可以将主机名替换为你要访问的天气预报网站的主机名,并根据需要更改请求的格式。
阅读全文