c语言实现http客户端示例代码
时间: 2023-09-25 18:09:26 浏览: 76
C语言实现https客户端
好的,我可以提供一个示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define HTTP_PORT 80
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <host>\n", argv[0]);
exit(1);
}
char *host = argv[1];
struct hostent *he = gethostbyname(host);
if (he == NULL) {
printf("Failed to resolve host %s\n", host);
exit(1);
}
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket");
exit(1);
}
struct sockaddr_in server_addr = {
.sin_family = AF_INET,
.sin_port = htons(HTTP_PORT),
.sin_addr = *((struct in_addr *)he->h_addr),
};
if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("connect");
exit(1);
}
char request[1024];
snprintf(request, sizeof(request), "GET / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", host);
if (send(sockfd, request, strlen(request), 0) == -1) {
perror("send");
exit(1);
}
char response[1024];
int n;
while ((n = recv(sockfd, response, sizeof(response) - 1, 0)) > 0) {
response[n] = '\0';
printf("%s", response);
}
if (n == -1) {
perror("recv");
exit(1);
}
close(sockfd);
return 0;
}
```
这个代码使用了C语言的socket API来实现一个HTTP客户端,可以向指定的主机发送GET请求并获取响应。请注意,该示例代码并不是一个完整的、可靠的HTTP客户端实现,仅供参考和学习。
阅读全文