c写一个tcp获取网页输入指定域名
时间: 2024-03-10 16:43:49 浏览: 21
下面是一个简单的示例程序,可以使用C语言的Socket编程获取网页输入指定域名的内容:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <hostname>\n", argv[0]);
return 1;
}
char *hostname = argv[1];
struct addrinfo hints, *result, *rp;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* TCP socket */
hints.ai_flags = 0;
hints.ai_protocol = 0; /* Any protocol */
int s = getaddrinfo(hostname, "http", &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
return 1;
}
int sockfd;
for (rp = result; rp != NULL; rp = rp->ai_next) {
sockfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sockfd == -1)
continue;
if (connect(sockfd, rp->ai_addr, rp->ai_addrlen) != -1)
break;
close(sockfd);
}
if (rp == NULL) {
fprintf(stderr, "Could not connect\n");
return 1;
}
freeaddrinfo(result);
char request[1024];
sprintf(request, "GET / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", hostname);
if (send(sockfd, request, strlen(request), 0) == -1) {
fprintf(stderr, "send error\n");
return 1;
}
char buf[1024];
int len;
while ((len = recv(sockfd, buf, 1024, 0)) > 0) {
fwrite(buf, len, 1, stdout);
}
close(sockfd);
return 0;
}
```
该程序使用了getaddrinfo函数获取目标地址信息,然后循环尝试连接,直到成功或者所有地址都尝试完毕。在成功连接后,构造HTTP GET请求并发送到目标主机,然后接收HTTP响应并输出到控制台。需要注意的是,该程序只是一个简单的示例,实际应用中还需要考虑错误处理、超时等问题。同时,如果需要获取指定域名的内容,需要在HTTP请求头中指定Host字段。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)