linux-http小程序

来源:互联网 发布:淘宝老七家 编辑:程序博客网 时间:2024/06/05 00:08

本程序比较简单,主要是使用htpp协议的GET命令来获取web根目录的信息。

程序接收到web服务端返回的程序后,在终端中显示,并且在当前目录创建一个文本来记录信息。

 

上图:

 

 

 

 

源码:

#include <signal.h>#include <sys/socket.h>#include <sys/types.h>#include <sys/time.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <netdb.h>#include <netinet/in.h>#include <arpa/inet.h>#include <netinet/ip.h>#include <netinet/ip_icmp.h>#include <errno.h>#include <fcntl.h>int main(int argc, char *argv[]){int sockfd,conn,filefd;int port = 80;char buffer[1024];char MsgBuf[2048];struct hostent *host;static struct sockaddr_in mysock;if(argc < 2){printf("usage:%s hostname/IP address\n",argv[0]);exit(1);}if((sockfd = socket(AF_INET,SOCK_STREAM,0))<0){perror("socket error!\n");exit(1);}if((host = gethostbyname(argv[1])) == NULL){perror("gethostbyname error");exit(1);}mysock.sin_family = AF_INET;mysock.sin_addr =  *((struct in_addr *)host->h_addr);mysock.sin_port = htons(port);printf("Msg: %s(%s)\n",argv[1],inet_ntoa(mysock.sin_addr));conn = connect(sockfd,(struct sockaddr*)&mysock,sizeof(mysock));if(conn < 0){perror("connect error!\n");close(sockfd);exit(1);}memset(&buffer,0,1024);memset(&MsgBuf,0,sizeof(MsgBuf));printf("send packeting.. \n");//sprintf(buffer,"GET / HTTP/1.1\r\nHost:%s\r\nUser-Agent: Mozilla/5.0 (X11; Linux i686; rv:22.0) Gecko/20100101 Firefox/22.0 Iceweasel/22.0\r\n\r\n",argv[1]);sprintf(buffer,"GET / HTTP/1.1\r\nHost:%s\r\nUser-Agent: Mozilla/5.0\r\n\r\n",argv[1]);if(write(sockfd,buffer,sizeof(buffer))<0){perror("write error!\n");close(sockfd);exit(1);}//printf("send success!\n");if((read(sockfd,MsgBuf,sizeof(MsgBuf)))<0){perror("read error!\n");exit(1);}if((filefd = creat("http.txt",S_IRUSR|S_IWUSR))<0){perror("creat file errno\n");}if((write(filefd,MsgBuf,sizeof(MsgBuf)))<0){perror("write file errno\n");}printf("%s",MsgBuf);close(sockfd);return 0;}

原创粉丝点击