头文件:
1 #pragma once 2 3 #include<stdio.h> 4 #include<unistd.h> 5 #include<string.h> 6 #include<stdlib.h> 7 #include<netinet/in.h> 8 9 #define SERVER_IP "192.168.0.22" 10 #define SERVER_PORT 10000 11 12 #define MAX_BUFFER_SIZE 255 13 #define LISTEN_QUEUE_SIZE 5 14 void Perror(char *str) 15 { 16 perror(str); 17 exit(1); 18 }
客户端代码:
1 #include"utili.h" 2 3 int main() 4 { 5 int sockCli = socket(AF_INET, SOCK_DGRAM, 0); 6 if(sockCli == -1) 7 Perror("socket"); 8 9 struct sockaddr_in addrSer,addrCli; 10 addrSer.sin_family = AF_INET; 11 addrSer.sin_port = htons(SERVER_PORT); 12 addrSer.sin_addr.s_addr = inet_addr(SERVER_IP); 13 14 socklen_t len = sizeof(struct sockaddr); 15 char sendbuf[MAX_BUFFER_SIZE]; 16 char recvbuf[MAX_BUFFER_SIZE]; 17 18 while(1) 19 { 20 printf("Cli:>"); 21 scanf("%s",sendbuf); 22 sendto(sockCli, sendbuf, strlen(sendbuf)+1, 0, (struct sockaddr*)&addrSer, len); 23 24 recvfrom(sockCli, recvbuf, MAX_BUFFER_SIZE, 0, (struct sockaddr*)&addrSer, &len); 25 printf("Ser:>%s\n",recvbuf); 26 27 } 28 29 close(sockCli); 30 return 0; 31 }
服务端代码:
1 #include"utili.h" 2 3 int main() 4 { 5 int sockSer = socket(AF_INET, SOCK_DGRAM, 0); 6 if(sockSer == -1) 7 Perror("socket"); 8 9 struct sockaddr_in addrSer,addrCli; 10 addrSer.sin_family = AF_INET; 11 addrSer.sin_port = htons(SERVER_PORT); 12 addrSer.sin_addr.s_addr = inet_addr(SERVER_IP); 13 14 socklen_t len = sizeof(struct sockaddr); 15 int res = bind(sockSer, (struct sockaddr*)&addrSer, len); 16 if(res == -1) 17 Perror("bind"); 18 19 char sendbuf[MAX_BUFFER_SIZE]; 20 char recvbuf[MAX_BUFFER_SIZE]; 21 22 while(1) 23 { 24 recvfrom(sockSer, recvbuf, MAX_BUFFER_SIZE, 0, (struct sockaddr*)&addrCli, &len); 25 printf("Cli:>%s\n",recvbuf); 26 27 printf("Ser:>"); 28 scanf("%s",sendbuf); 29 sendto(sockSer, sendbuf, strlen(sendbuf)+1, 0, (struct sockaddr*)&addrCli, len); 30 } 31 32 close(sockSer); 33 return 0; 34 }