网络编程Socket UDP
图表流程
linux udp测试代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//server.c #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/un.h> #include <sys/socket.h> #include <sys/unistd.h> #include <arpa/inet.h> #define PORT 8999 #define MAXSIZE 4096 int main(int argc, char *argv[]) { int sockfd, addr_len; struct sockaddr_in serv_addr, clnt_addr; char recvmsg[MAXSIZE], sendmsg[MAXSIZE]; sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("socket error"); return -1; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); serv_addr.sin_addr.s_addr = INADDR_ANY; memset(&(serv_addr.sin_zero), 0,8); if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) < 0) { perror("bind err"); return -1; } while(1) { memset(sendmsg, 0, MAXSIZE); memset(recvmsg, 0, MAXSIZE); addr_len = sizeof(struct sockaddr); /* 所谓的非阻塞I/O */ if (recvfrom(sockfd, recvmsg, MAXSIZE, 0, (struct sockaddr *)&clnt_addr, &addr_len) < 0) { perror("recv"); continue; } printf("begin to accept\n"); printf("recv from %s : %s\n", inet_ntoa(clnt_addr.sin_addr), recvmsg); strcpy(sendmsg, "who are you ?? Let me cc!"); sendto(sockfd, sendmsg, strlen(sendmsg) + 1, 0, (struct sockaddr *)&clnt_addr, addr_len); } return 0; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//client.c #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/un.h> #include <sys/socket.h> #include <sys/unistd.h> #include <arpa/inet.h> #define PORT 8999 #define DESIP "192.168.23.109" #define MAXSIZE 4096 int main(int argc, char *argv[]) { int sockfd, addr_len; struct sockaddr_in des_addr; char sendmsg[MAXSIZE], recvmsg[MAXSIZE]; sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("socket error"); return -1; } des_addr.sin_family = AF_INET; des_addr.sin_port = htons(PORT); des_addr.sin_addr.s_addr = inet_addr(DESIP); //bzero(&(des_addr.sin_zero), 8); memset(&(des_addr.sin_zero), 0,8); while (1) { memset(recvmsg, 0, MAXSIZE); memset(sendmsg, 0, MAXSIZE); printf("input:\n"); gets(sendmsg); if (strcmp(sendmsg, "quit") == 0) { close(sockfd); printf("close connection\n"); return -1; } if (sendto(sockfd, sendmsg, strlen(sendmsg) + 1, 0, (struct sockaddr *)&des_addr, sizeof(struct sockaddr)) < 0) { perror("sendto"); continue; } printf("send ok...\n"); while (1) {/* 所谓的非阻塞I/O */ addr_len = sizeof(struct sockaddr); if (recvfrom(sockfd, recvmsg, MAXSIZE, 0, (struct sockaddr *)&des_addr, &addr_len) < 0) { continue; } printf("recv from %s : %s\n", inet_ntoa(des_addr.sin_addr), recvmsg); break; } } return 0; }
参考资料: