简单的udp客户服务端程序
服务端程序:server.c
1 #include <string.h> 2 #include <unistd.h> 3 #include <arpa/inet.h> 4 #include <sys/types.h> 5 #include <netinet/in.h> 6 #include <stdio.h> 7 8 9 10 11 #define PORT 12345 12 13 int main() 14 { 15 struct sockaddr_in server_addr, client_addr; 16 char msg[1024]; 17 int len; 18 static count = 1; 19 int fd = socket(AF_INET, SOCK_DGRAM, 0); 20 bzero(&server_addr, sizeof(struct sockaddr_in)); 21 22 server_addr.sin_family = AF_INET; 23 server_addr.sin_port = htons(PORT); 24 server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); 25 26 bind(fd, (struct sockaddr*)&server_addr, sizeof(struct sockaddr_in)); 27 28 socklen_t addr_len; 29 while(1) 30 { 31 bzero(msg, sizeof(msg)); 32 addr_len = sizeof(client_addr); 33 len = recvfrom(fd, msg, sizeof(msg), 0, (struct sockaddr*)&client_addr, &addr_len);//百度百科直接搜 34 printf("%d: ", len); 35 printf("msg from: %s\n", inet_ntoa(client_addr.sin_addr)); 36 printf("msg: %s\n", msg); 37 sendto(fd, msg, len, 0, (struct sockaddr*)&client_addr, addr_len);//百度百科直接搜 38 39 } 40 41 return 0; 42 43 }
客户端程序:client.c
1 #include <string.h> 2 #include <unistd.h> 3 #include <arpa/inet.h> 4 #include <sys/types.h> 5 #include <netinet/in.h> 6 #include <stdio.h> 7 8 9 10 11 #define PORT 12345 12 #define IP "127.0.0.1" 13 int main() 14 { 15 struct sockaddr_in server_addr; 16 char msg[1024]; 17 int len; 18 int fd = socket(AF_INET, SOCK_DGRAM, 0); //创建socket,注意udp创建的是数据包套接字,SOCK_DGRAM 19 if(fd < 0) 20 { 21 printf("socket error\n"); 22 } 23 bzero(&server_addr, sizeof(struct sockaddr_in)); //相当于memset(&server_addr, 0, sizeof(struct sockaddr_in)); 24 25 //指定服务端的端口和ip 26 server_addr.sin_family = AF_INET; 27 server_addr.sin_port = htons(PORT); 28 29 inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr); 30 31 32 socklen_t addr_len; 33 int ret; 34 int n; 35 while(1) 36 { 37 //int n = read(STDIN_FILENO, msg, sizeof(msg)); 38 fgets(msg, 1024, stdin); //用户输入字符串,fgets会读入字符'\n' 39 printf(" msg: %s", msg); 40 //发送到server端 41 ret = sendto(fd, msg, strlen(msg), 0, (struct sockaddr*)&server_addr, sizeof(server_addr)); 42 printf("ret: %d\n", ret); 43 //接收从服务端收到的字符串 44 n = recvfrom(fd, msg, sizeof(msg), 0, NULL, NULL); 45 printf("n=%d\n", n); 46 msg[n]='\0';// 收到的字符串后面没有'\0',无法printf输出,所以在字符串后添加'\0' 47 printf("%s", msg); 48 printf("__________________________________\n"); 49 50 } 51 52 return 0; 53 54 }