1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <errno.h> 5 #include <sys/socket.h> 6 #include <sys/types.h> 7 #include <netinet/in.h> 8 #include <unistd.h> 9 #include <arpa/inet.h> 10 int main() 11 { 12 printf("a server "); 13 int listenfd = socket(AF_INET, SOCK_STREAM, 0);//创建一个socket描述符,唯一标识一个socket,socket()返回文件描述符 14 0,1,2分别表示标准输入、标准输出、标准错误,所以其他打开的文件描述符都会大于2, 错误时就返回 -1 15 if(listenfd == -1) 16 { 17 printf("error:socket "); 18 return 0; 19 } 20 21 struct sockaddr_in addr; 22 addr.sin_family = AF_INET;//IPV4 23 addr.sin_port = htons(8000);//host to net,主机字节转为网络字节 24 addr.sin_addr.s_addr = INADDR_ANY;//指定ip地址:所有地址 25 if(bind(listenfd, (struct sockaddr*)&addr, sizeof(addr)) == -1)//bind()把地址和端口号组合赋给socket 26 { 27 printf("error:bind() "); 28 return 0; 29 } 30 31 if(listen(listenfd, 5) == -1)//int listen( int sockfd/*用于标识一个已捆绑未连接套接口的描述字*/, 32 int backlog/*等待连接队列最大长度*/); 33 { 34 printf("error:listen "); 35 return 0; 36 } 37 38 int conn;//客户端套接字描述字 39 char clientIP[INET_ADDRSTRLEN]; 40 struct sockaddr_in clientAddr; 41 socklen_t clientAddrLen = sizeof(clientAddr); 42 while(1) 43 { 44 printf("listening...... "); 45 conn = accept(listenfd, (struct sockaddr*)&clientAddr, &clientAddrLen);//监听到之后,调用accept() 46 if(conn < 0) 47 { 48 printf("error:accept "); 49 continue; 50 } 51 inet_ntop(AF_INET/*IPV4*/, &clientAddr.sin_addr/*source*/, clientIP/*destination*/, INET_ADDRSTRLEN/*IP长度*/); 52 /*在点分十进制和二进制整数转换*/ 53 printf("connect %s ",clientIP);//IP:port 54 55 char buff[255]; 56 while(1) 57 { 58 for(int i=0; i<255; ++i)buff[i]=0; 59 int len = recv(conn, buff/*存放接收数据*/, sizeof(buff), 0/*一般置零*/); 60 buff[len] = '