linux下udp简单例子:
服务器:
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/types.h> #include <sys/time.h> #include <unistd.h> #include <string.h> #include <arpa/inet.h> #define Myport 2234 int main(void) { int sock; char recvbuf[100] = {0}; char sendbuf[100] = {0}; struct sockaddr_in cliaddr; int clilen = sizeof(struct sockaddr); int ret = 0; if( (sock=socket(AF_INET, SOCK_DGRAM, 0)) <0 ) { printf("socket err\n"); return -1; } struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(struct sockaddr_in)); servaddr.sin_family = PF_INET; servaddr.sin_port = htons(Myport); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(sock, (struct sockaddr*)&servaddr, sizeof(servaddr)) <0) { printf("bind err\n"); perror("bind"); return -1; } printf("net server starting \n"); struct timeval tv = {0}; while(1) { ret = recvfrom(sock, recvbuf, sizeof(recvbuf), 0, (struct sockaddr *)&cliaddr, &clilen ); if(ret <0) { printf("recvfrom err"); return -1; } getsockname(sock, (struct sockaddr*)&cliaddr, (socklen_t*)&clilen ); printf("recv client addr : %s data %s\n",inet_ntoa(cliaddr.sin_addr), recvbuf); gettimeofday(&tv, NULL); memcpy(sendbuf, &tv, sizeof(struct timeval)); ret = sendto(sock, sendbuf, sizeof(struct timeval), 0, (struct sockaddr *)&cliaddr, clilen ); if(ret <0){ //printf("send err %d\n", ret); perror("socket"); return -1; } printf(" second :%ld\n ms: %ld\n us: %ld\n", tv.tv_sec, tv.tv_sec*1000+tv.tv_usec/1000,\ tv.tv_usec); }//while(true) close(sock); return 0; }
客户端
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <sys/time.h> #define Myport 2234 char *SERVERIP = "192.168.229.129"; int main(void) { struct sockaddr_in servaddr; char sendbuf[100] = {0}; struct timeval recvbuf; int sock; int ret = 0; if( (sock=socket(AF_INET, SOCK_DGRAM, 0)) <0 ) { printf("sock err\n"); return -1; } memset(&servaddr, 0, sizeof(servaddr) ); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(Myport); servaddr.sin_addr.s_addr = inet_addr(SERVERIP); while(1) { memset(&recvbuf,0, sizeof(recvbuf) ); printf("start sleep\n"); sendto(sock, "muchx", 5, 0, (struct sockaddr*)&servaddr, sizeof(servaddr) ); recvfrom(sock, (struct timeval*)&recvbuf, sizeof(recvbuf), 0, NULL, NULL); printf("s:%ld\n ms:%ld\n us:%ld\n", recvbuf.tv_sec,recvbuf.tv_sec*1000+recvbuf.tv_usec/1000,recvbuf.tv_usec ); sleep(4); sendto(sock, "muchx", 5, 0, (struct sockaddr*)&servaddr, sizeof(servaddr) ); recvfrom(sock, (struct timeval*)&recvbuf, sizeof(recvbuf), 0, NULL, NULL); printf("s:%ld\n ms:%ld\n us:%ld\n", recvbuf.tv_sec,recvbuf.tv_sec*1000+recvbuf.tv_usec/1000,\ recvbuf.tv_usec ); printf("end sleep\n"); } return 0; }
服务器打印:
客户端打印: