两者代码基本一致
关于套接字:
甲方:
1 #include <stdio.h> 2 #include <string.h> 3 #include <netinet/in.h> 4 #include <stdlib.h> 5 #include <sys/socket.h> 6 #include <fcntl.h> 7 8 int main() 9 { 10 int ret = 0; 11 int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); 12 if(fd < 0){ 13 perror("socket"); 14 exit(EXIT_FAILURE); 15 } 16 struct sockaddr_in gg; 17 gg.sin_family = AF_INET; 18 gg.sin_port = htons(9527); 19 gg.sin_addr.s_addr = inet_addr("192.168.1.10"); 20 ret = bind(fd, (struct sockaddr *)&gg, 16); 21 if(ret < 0){ 22 perror("bind"); 23 return 1; 24 } 25 unsigned char buff[1024] = {0}; 26 unsigned char data[1024] = {0}; 27 struct sockaddr_in mm; 28 mm.sin_family = AF_INET; 29 mm.sin_port = htons(9528); 30 mm.sin_addr.s_addr = inet_addr("192.168.1.10"); 31 int mm_len = 0; 32 while(1){ 33 fd_set st; 34 FD_ZERO(&st); 35 FD_SET(fd, &st); 36 FD_SET(0, &st); 37 ret = select(fd+1, &st, 0, 0, 0); 38 if(ret < 0){ 39 perror("select"); 40 return 1; 41 } 42 if(FD_ISSET(fd, &st)){ 43 memset(buff, 0, 1024); 44 ret = recvfrom(fd, buff, 1024, 0, (struct sockaddr *)&mm, &mm_len); 45 if(ret < 0){ 46 perror("recvfrom"); 47 exit(EXIT_FAILURE); 48 } 49 printf("gg said :%s", buff); 50 } 51 if(FD_ISSET(0, &st)){ 52 memset(data, 0, 1024); 53 read(0, data, 1024); 54 ret = sendto(fd, data, strlen(data), 0, (struct sockaddr *)&mm, 16); 55 if(ret < 0){ 56 perror("sendto"); 57 exit(EXIT_FAILURE); 58 } 59 } 60 61 } 62 close(fd); 63 }
乙方:
1 #include <stdio.h> 2 #include <string.h> 3 #include <netinet/in.h> 4 #include <stdlib.h> 5 #include <sys/socket.h> 6 #include <fcntl.h> 7 8 int main() 9 { 10 int ret = 0; 11 int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); 12 if(fd < 0){ 13 perror("socket"); 14 exit(EXIT_FAILURE); 15 } 16 struct sockaddr_in mm; 17 mm.sin_family = AF_INET; 18 mm.sin_port = htons(9528); 19 mm.sin_addr.s_addr = inet_addr("192.168.1.10"); 20 ret = bind(fd, (struct sockaddr *)&mm, 16); 21 if(ret < 0){ 22 perror("bind"); 23 return 1; 24 } 25 unsigned char buff[1024] = {0}; 26 unsigned char data[1024] = {0}; 27 struct sockaddr_in gg; 28 gg.sin_family = AF_INET; 29 gg.sin_port = htons(9527); 30 gg.sin_addr.s_addr = inet_addr("192.168.1.10"); 31 int gg_len = 0; 32 while(1){ 33 fd_set st; 34 FD_ZERO(&st); 35 FD_SET(fd, &st); 36 FD_SET(0, &st); 37 ret = select(fd+1, &st, 0, 0, 0); 38 if(ret < 0){ 39 perror("select"); 40 return 1; 41 } 42 if(FD_ISSET(fd, &st)){ 43 memset(buff, 0, 1024); 44 ret = recvfrom(fd, buff, 1024, 0, (struct sockaddr * )&gg, &gg_len); 45 if(ret < 0){ 46 perror("recvfrom"); 47 exit(EXIT_FAILURE); 48 } 49 printf("mm said :%s", buff); 50 } 51 if(FD_ISSET(0, &st)){ 52 memset(data, 0, 1024); 53 read(0, data, 1024); 54 ret = sendto(fd, data, strlen(data), 0, (struct sockaddr *)&gg, 16); 55 if(ret < 0){ 56 perror("sendto"); 57 exit(EXIT_FAILURE); 58 } 59 } 60 } 61 close(fd); 62 } ~
时间: 2024-11-05 20:50:21