1、服务器端
1 #include<stdio.h> 2 #include<sys/socket.h>//套接字 3 #include<netinet/in.h> 4 #include<string.h> 5 #include<stdlib.h> 6 #include<arpa/inet.h>//字节序转换 7 #include<unistd.h> 8 9 //可以正常运行了; 10 11 #define SERVPORT 6666 12 13 int main() 14 { 15 int listenfd,connfd;//两个套接口 16 struct sockaddr_in servaddr,cliaddr; 17 socklen_t clilen;//这个定义的客户端套接字长度 18 char buf[100] = {0}; 19 int bytes_recv; 20 //建立套接口 21 //第三个参数默认为0 22 listenfd = socket(AF_INET,SOCK_STREAM,0); 23 24 //配置地址 25 bzero(&servaddr,sizeof(servaddr)); 26 servaddr.sin_family = AF_INET; 27 servaddr.sin_port = htons(SERVPORT); 28 servaddr.sin_addr.s_addr = htonl(INADDR_ANY);//或者是单一地址 29 30 int opt = 1; 31 setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));//端口复用 32 33 bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));//强制类型转换 34 35 listen(listenfd,1024);//队列数 36 37 for(;;)//这个循环结束不了,其实服务器也不用停啊 38 { 39 clilen = sizeof(cliaddr); 40 connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&clilen); 41 printf("accept client ip is %s,port is %u\n",inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port);//port短整型 42 43 while(1) 44 { 45 bzero(buf,sizeof(buf)); 46 bytes_recv = recvfrom(connfd,buf,sizeof(buf),0,(struct sockaddr *)&cliaddr,&clilen); 47 if(0 == bytes_recv) 48 { 49 printf("client offline!"); 50 break; 51 } 52 sendto(connfd,buf,bytes_recv,0,(struct sockaddr *)&cliaddr,clilen); 53 } 54 close(connfd); 55 } 56 57 close(listenfd); 58 59 return 0; 60 }
2、客户端
1 #include<stdio.h> 2 #include<sys/socket.h> 3 #include<netinet/in.h> 4 #include<string.h> 5 #include<stdlib.h> 6 #include<arpa/inet.h>//字节序转换 7 #include<unistd.h> 8 9 #define SERVPORT 6666 10 11 int main(int argc,char **argv) 12 { 13 int sockfd; 14 struct sockaddr_in servaddr; 15 int bytes_recv; 16 char readline[100]; 17 char sendline[100]; 18 19 // if(argc != 2) 20 // { 21 // printf("please input the IP\n"); 22 // exit(0); 23 //} 24 //创建套接字 25 sockfd = socket(AF_INET,SOCK_STREAM,0); 26 27 bzero(&servaddr,sizeof(servaddr)); 28 servaddr.sin_family = AF_INET; 29 servaddr.sin_port = htons(SERVPORT); 30 //inet_aton(argv[1],&servaddr.sin_addr); 31 servaddr.sin_addr.s_addr = inet_addr("192.168.138.137");//直接绑定服务器端地址 32 33 34 //连接 35 connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); 36 while((fgets(sendline,100,stdin)) != NULL)//等一会可以结束 37 {//减一是因为fgets读入了\n; 第四个参数好像也是flag 38 sendto(sockfd,sendline,strlen(sendline)-1,0,(struct sockaddr *)&servaddr,sizeof(servaddr)); 39 bytes_recv = recvfrom(sockfd,readline,sizeof(readline),0,NULL,NULL); 40 41 printf("recv character:%d\n",bytes_recv); 42 43 bzero(readline,sizeof(readline)); 44 bzero(sendline,sizeof(readline)); 45 46 } 47 48 49 close(sockfd); 50 51 52 return 0; 53 }
标签:struct,TCP,servaddr,之套,sin,sizeof,include,recv,接字 From: https://www.cnblogs.com/gunancheng/p/17542879.html