udp写的程序相比tcp简单一些,在socket()与bind()之后,不需要connect(),accept()等步骤,直接简化为了sendto()与recvfrom()。
编译运行同前面的tcp。
/*client_udp.c*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #define MAXLINE 4096 #define SERV_PORT 9877 void process(FILE *fp, int sockfd, const struct sockaddr *pservaddr, socklen_t servlen) { int n; char send[MAXLINE], recv[MAXLINE]; while (fgets(send, MAXLINE, fp) != NULL) { sendto(sockfd, send, strlen(send), , pservaddr, servlen); n = recvfrom(sockfd, recv, MAXLINE, , NULL, NULL); recv[n] = ; fputs(recv, stdout); } } int main(int argc, char *argv[]) { int sockfd; struct sockaddr_in servaddr; ) { fprintf(stderr, "usage: client_udp <IP>\n"); exit(); } memset(&servaddr, , sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(SERV_PORT); inet_pton(AF_INET, argv[], &servaddr.sin_addr); sockfd = socket(AF_INET, SOCK_DGRAM, ); process(stdin, sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); exit(); }
/*server_udp.c*/ #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #define MAXLINE 4096 #define SERV_PORT 9877 void process(int sockfd, struct sockaddr *pcliaddr, socklen_t clilen) { int n; socklen_t len; char mesg[MAXLINE]; ) { len = clilen; n = recvfrom(sockfd, mesg, MAXLINE, , pcliaddr, &len); sendto(sockfd, mesg, n, , pcliaddr, len); } } int main(int argc, char *argv[]) { int sockfd; struct sockaddr_in servaddr, cliaddr; sockfd = socket(AF_INET, SOCK_DGRAM, ); memset(&servaddr, , sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); process(sockfd, (struct sockaddr *)&cliaddr, sizeof(cliaddr)); }