C语言使用Socket发起HTTP请求
[c]
#include <string.h>
#include <sys/socket.h>
#include <resolv.h>
int request(char *host, int port){
int sockfd;
struct sockaddr_in server;
char buffer[2048];
char *request = "GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n";
sockfd = socket(AF_INET, SOCK_STREAM, 0);
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = inet_addr(host);
connect(sockfd, (struct sockaddr*)&server, sizeof(server));
send(sockfd, request, strlen(request), 0);
recv(sockfd, buffer, sizeof(buffer), 0);
close(sockfd);
printf("%s", buffer);
return 0;
}
void main(){
request("219.239.21.42", 80);
}
[/c]
下载源码