0.UDP客户端
1 /** 2 udpclient.c 3 */ 4 #include <stdio.h> 5 #include <unistd.h> 6 #include <sys/socket.h> 7 #include <sys/types.h> 8 #include <arpa/inet.h> 9 #include <string.h> 10 #include <strings.h> 11 12 #define PORT 8111 13 #define MSG_LEN 1024 14 15 int main(int argc, char* argv[]) 16 { 17 int sockfd; 18 char send_buf[MSG_LEN] = { 0 }; 19 char recv_buf[MSG_LEN + 1] = { 0 }; 20 struct sockaddr_in serv_addr; 21 22 if (argc != 2) { 23 printf("usage: udpclient <ip address> "); 24 _exit(-1); 25 } 26 27 bzero(&serv_addr, sizeof(serv_addr)); 28 serv_addr.sin_family = AF_INET; 29 serv_addr.sin_port = htons(PORT); 30 inet_pton(AF_INET, argv[1], &serv_addr.sin_addr); 31 sockfd = socket(AF_INET, SOCK_DGRAM, 0); 32 33 while (gets(send_buf) != NULL) { 34 sendto(sockfd, 35 send_buf, 36 strlen(send_buf), 37 0, 38 (struct sockaddr *)&serv_addr, 39 sizeof(serv_addr)); 40 int n = recvfrom(sockfd, recv_buf, MSG_LEN, 0, NULL, NULL); 41 if (n > 0) { 42 recv_buf[n] = '