1 #include <stdio.h> 2 #include <sys/types.h> 3 #include <sys/socket.h> 4 #include <netinet/in.h> 5 #include <string.h> 6 7 #define SERVER_PORT 8888 8 #define BUFF_LEN 512 9 #define SERVER_IP "172.0.5.182" 10 11 12 void udp_msg_sender(int fd, struct sockaddr* dst) 13 { 14 15 socklen_t len; 16 struct sockaddr_in src; 17 while(1) 18 { 19 char buf[BUFF_LEN] = "TEST UDP MSG!\n"; 20 len = sizeof(*dst); 21 printf("client:%s\n",buf); //打印自己发送的信息 22 sendto(fd, buf, BUFF_LEN, 0, dst, len); 23 memset(buf, 0, BUFF_LEN); 24 recvfrom(fd, buf, BUFF_LEN, 0, (struct sockaddr*)&src, &len); //接收来自server的信息 25 printf("server:%s\n",buf); 26 sleep(1); //一秒发送一次消息 27 } 28 } 29 30 /* 31 client: 32 socket-->sendto-->revcfrom-->close 33 */ 34 35 int main(int argc, char* argv[]) 36 { 37 int client_fd; 38 struct sockaddr_in ser_addr; 39 40 client_fd = socket(AF_INET, SOCK_DGRAM, 0); 41 if(client_fd < 0) 42 { 43 printf("create socket fail!\n"); 44 return -1; 45 } 46 47 memset(&ser_addr, 0, sizeof(ser_addr)); 48 ser_addr.sin_family = AF_INET; 49 //ser_addr.sin_addr.s_addr = inet_addr(SERVER_IP); 50 ser_addr.sin_addr.s_addr = htonl(INADDR_ANY); //注意网络序转换 51 ser_addr.sin_port = htons(SERVER_PORT); //注意网络序转换 52 53 udp_msg_sender(client_fd, (struct sockaddr*)&ser_addr); 54 55 close(client_fd); 56 57 return 0; 58 }
以上的框架用于一台主机不同端口的UDP通信,现象如下:
我们先建立server端,等待服务;然后我们建立client端请求服务。
server端:
client端: