转自 http://blog.csdn.net/mqwind/article/details/4814842
环境:linux gcc
本文以请求百度首页为例,步骤如下:
1:ping www.baidu.com 获取ip地址220.181.112.244
2:vi c_socket_http.c 代码如下:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(){
int sockfd;
int len;
struct sockaddr_in address;
int result;
char *strings="GET / HTTP/1.1\r\nHost: 220.181.112.244\r\nConnection: Close\r\n\r\n";
char ch;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("220.181.112.244");
address.sin_port = htons(80);
len = sizeof(address);
result = connect(sockfd, (struct sockaddr *)&address, len);
if(result == -1){
perror("oops: client1");
return 1;
}
write(sockfd,strings,strlen(strings));
while(read(sockfd,&ch, 1)){
printf("%c", ch);
}
close(sockfd);
return 0;
}
3: gcc -o c_socket_http c_socket_http.c
4:./c_socket_http 输出结果
注意:本文中的代码和原文中的代码有点出入,原文中少引入了string.h头文件、还有就是/r/n不对,应该是\r\n。
3754

被折叠的 条评论
为什么被折叠?



