1、receive [cpp] #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #define BUF_SIZE 512 int create_udp_socket(char *ip, int port){ int onOff = 1; struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(ip); //addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(port); int sockfd; if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { return(-1); } fcntl(sockfd, F_SETFD, FD_CLOEXEC); setsockopt(sockfd,SOL_SOCKET, SO_REUSEADDR, (const void *)&onOff, sizeof(onOff)); if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { close(sockfd); return(-1); } return sockfd; } void listen_udp(int socket){ socklen_t sin_len; char msg_buffer[BUF_SIZE]; struct sockaddr_in sin; sin_len=sizeof(sin); fd_set rfds; struct timeval tv; int retval; int rlen = 0; int socket_descriptor; socket_descriptor = socket; while(1){ FD_ZERO(&rfds); FD_SET(socket_descriptor, &rfds); tv.tv_sec = 4; tv.tv_usec = 0; retval = select(socket_descriptor+1, &rfds, NULL, NULL, &tv); if (retval == -1){ printf("select error %d %s\n",socket_descriptor,strerror(errno)); break; } else if (retval){ memset(msg_buffer, 0, BUF_SIZE); if(FD_ISSET(socket_descriptor, &rfds)){ rlen = recvfrom(socket_descriptor, msg_buffer, BUF_SIZE, 0, (struct sockaddr *)&sin, &sin_len); if(rlen > 0){ printf("recv %s \n", msg_buffer); } else{ printf("rlen : %d\n", rlen); } } } } close(socket_descriptor); } void main(void){ int socket; socket = create_udp_socket("127.0.0.1",1000); listen_udp(socket); } 2、send [cpp] #include"common.h" #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> int send_message_to_player( const char* ip_address, const unsigned int port, char *info ) { struct sockaddr_in servaddr; int sockfd; if (!ip_address) { return 1; } sockfd = socket(AF_INET,SOCK_DGRAM, 0); if (sockfd < 0) { printf("error opening socket"); return 1; } memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr(ip_address); servaddr.sin_port=htons(port); sendto(sockfd, info, strlen(info), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)); close(sockfd); www.2cto.com return 0; } void main(void) { char buf[]="<info title=\"test\"><status>1</status><message>12345</message><info>"; send_message_to_player("127.0.0.1",1000,buf); }