标签:
1 #include<sys/types.h> 2 #include<sys/socket.h> 3 #include<netinet/in.h> 4 #include<arpa/inet.h> 5 #include<unistd.h> 6 #include<string.h> 7 #include<stdlib.h> 8 #include<stdio.h> 9 #define PORT 2345 10 11 12 int main(void) 13 { 14 char msgbuf[256]; 15 int sockfd,newsockfd; 16 struct sockaddr_in addr; 17 int addr_len=sizeof(struct sockaddr_in); 18 if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0) 19 { 20 perror("socket created error!"); 21 exit(1); 22 } 23 else 24 { 25 printf("socket created successfully!\nsocket id:%d\n",sockfd); 26 } 27 28 bzero(&addr,sizeof(struct sockaddr_in)); 29 addr.sin_family=AF_INET; 30 addr.sin_port=htons(PORT); 31 addr.sin_addr.s_addr=htonl(INADDR_ANY); 32 if(bind(sockfd,(struct sockaddr *)(&addr),sizeof(struct sockaddr))<0) 33 { 34 perror("bind error!"); 35 exit(1); 36 } 37 else 38 { 39 printf("bind port successfully!\nlocal port:%d\n",PORT); 40 } 41 42 if(listen(sockfd,5)<0) 43 { 44 perror("listen error!"); 45 exit(1); 46 } 47 else 48 { 49 printf("listening ........\n"); 50 } 51 52 if((newsockfd=accept(sockfd,(struct sockaddr *)(&addr),&addr_len))<0) 53 { 54 perror("accept error!"); 55 } 56 else 57 { 58 printf("connect from %s\n",inet_ntoa(addr.sin_addr)); 59 if(read(newsockfd,msgbuf,sizeof(msgbuf))<=0) 60 { 61 perror("accept error!"); 62 } 63 else 64 { 65 printf("message:\n%s \n",msgbuf); 66 } 67 } 68 69 return 0; 70 }
程序运行结果:
1 socket created successfully! 2 socket id:3 3 bind port successfully! 4 local port:2345 5 listening ........ 6 connect from 192.168.83.1 7 message: 8 GET / HTTP/1.1 9 Host: 192.168.83.129:2345 10 Connection: keep-alive 11 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 12 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.0.0 Sa
标签:
原文地址:http://www.cnblogs.com/wireless-dragon/p/5186698.html