linux下纯C简单的HTTP POST请求 客户端模型 ---经典收藏,源代码打包httppost.tar,感谢博主
c直接访问网页
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <stdarg.h> 5 #include <sys/socket.h> 6 #include <netinet/in.h> 7 #include <netdb.h> 8 9 int htconnect(char *host, int port){ 10 int white_sock; 11 struct hostent * site; 12 struct sockaddr_in me; 13 site = gethostbyname(host); 14 if (site==NULL) return -2; 15 white_sock = socket(AF_INET,SOCK_STREAM,0); 16 if (white_sock <0) return -1; 17 memset(&me, 0, sizeof(struct sockaddr_in)); 18 memcpy(&me.sin_addr, site-> h_addr_list[0], site-> h_length); 19 me.sin_family = AF_INET; 20 me.sin_port = htons(port); 21 return (connect(white_sock, (struct sockaddr *)&me,sizeof(struct sockaddr)) <0) ? -1 : white_sock; 22 } 23 24 int htsend(int sock, char *fmt, ...){ 25 char BUF[1024]; 26 va_list argptr; 27 va_start(argptr,fmt); 28 vsprintf(BUF,fmt,argptr); 29 va_end(argptr); 30 printf(BUF); 31 return send(sock,BUF,strlen(BUF),0); 32 } 33 34 int main(int argc,char **argv){ 35 int black_sock; 36 char bugs_bunny[3]; 37 if (argc<2){ 38 printf( "Please input the hostName. Example:\n %s www.sohu.com\n ",argv[0]); 39 return; 40 } 41 black_sock = htconnect(argv[1],80); 42 if (black_sock <1)return; 43 htsend(black_sock, "GET / HTTP/1.0\n"); 44 htsend(black_sock, "Host: %s\n", argv[1]); 45 htsend(black_sock, "\n"); 46 //htsend(black_sock, "%c ", 10); 47 while (read(black_sock, bugs_bunny, 1)> 0) 48 printf( "%c",bugs_bunny[0]); 49 printf( "\n "); 50 close(black_sock); 51 }