1 #include<stdlib.h> 2 #include<string.h> 3 #include<stdio.h> 4 #include<sys/socket.h> 5 #include<arpa/inet.h> 6 #include<sys/types.h> 7 #include<netinet/in.h> 8 #define SERVER_PORT 8000 9 int main() 10 { 11 struct sockaddr_in serveraddr,clientaddr; 12 //1,socket() 13 //2,bind() 14 //3,listen() 15 //4,accept() 16 char ipstr[128]; 17 int sockfd,addrlen,confd; 18 sockfd=socket(AF_INET,SOCK_STREAM,0); 19 20 bzero(&serveraddr,sizeof(serveraddr)); 21 serveraddr.sin_family=AF_INET; 22 serveraddr.sin_addr.s_addr=htonl(INADDR_ANY); 23 serveraddr.sin_port=htons(SERVER_PORT); 24 25 bind(sockfd,(struct sockaddr *)&serveraddr,sizeof(serveraddr)); 26 27 listen(sockfd,128); 28 while(1){ 29 addrlen=sizeof(clientaddr); 30 confd=accept(sockfd,(struct sockaddr *)&clientaddr,&addrlen); 31 32 printf("client ip %s port %d ",inet_ntop(AF_INET,&clientaddr.sin_addr.s_addr,ipstr,sizeof(ipstr)),ntohs(clientaddr.sin_port)); 33 34 //connet with client 35 close(confd); 36 } 37 38 close(sockfd); 39 40 return 0; 41 }