标签:
1 #include<stdio.h> 2 #include<string.h> 3 #include<math.h> 4 #include<iostream> 5 #include<algorithm> 6 #include<queue> 7 #include<vector> 8 #include<set> 9 #include<stack> 10 #include<string> 11 #include<sstream> 12 #include<map> 13 #include<cctype> 14 #include<limits.h> 15 #include<stdlib.h> 16 #include<fstream> 17 #include<unistd.h> 18 #include<arpa/inet.h> 19 #include<windows.h> 20 #include<sys/scoket.h> 21 using namespace std; 22 int main() 23 { 24 int serv_sock,clnt_sock; 25 struct sockaddr_in serv_addr; 26 struct sockaddr_in clnt_addr; 27 socklen_t clnt_addr_size; 28 char message[]="hello world!"; 29 if(argc!=2) 30 { 31 printf("Usage : %s <port>\n",argv[0]); 32 exit(1); 33 } 34 serv_sock=socket(PF_INET,SOCK_STREAM,0); 35 if(serv_sock==-1) 36 error_handling("socket() error"); 37 memset(&serv_addr,0,sizeof(serv_addr)); 38 serv_addr.sin_family=AF_INET; 39 serv_addr.sin_addr.s_addr=htonl(INADDR_ANY); 40 serv_addr.sin_port=htons(atoi(argv[1])); 41 if(bind(serv_sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr))==-1) 42 error_handling("bind() error"); 43 if(listen(serv_sock,5)==-1) 44 error_handling("listen() error"); 45 clnt_addr_size=sizeof(clnt_addr); 46 clnt_sock=accept(serv_sock,(struct sockaddr*)&clnt_addr,&clnt_addr_size); 47 if(clnt_sock==-1) 48 error_handling("accept() error"); 49 write(clnt_sock,message,sizeof(message)); 50 close(clnt_sock); 51 close(clnt_sock); 52 return 0; 53 } 54 void error_hangling(char *message) 55 { 56 fputs(message,stderr); 57 fputc(‘\n‘,stderr); 58 exit(1); 59 }
标签:
原文地址:http://www.cnblogs.com/A-FM/p/5475139.html