//this socket is intend to use as a simple server int main() { puts("start main server....");
//init windows socket init_win_socket();
SOCKET main_sock_fd; struct sockaddr_in main_soc_addr; // my address information struct sockaddr_in client_soc_addr; // connector's address information
int addr_len; int numbytes; char buf[MAXBUFLEN]; int ret=0; //create the sock if ((main_sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { puts("CREATE SOCK ERROR:"); }
//configure sockaddr_in main_soc_addr.sin_family = AF_INET; // host byte order main_soc_addr.sin_port = htons(MYPORT); // short, network byte order main_soc_addr.sin_addr.s_addr= htonl(INADDR_ANY); // automatically fill with my IP memset(main_soc_addr.sin_zero, '\0', sizeof (main_soc_addr.sin_zero));
//bind the socket ret = bind(main_sock_fd, (struct sockaddr *)&main_soc_addr, sizeof main_soc_addr); if ( ret == -1) { puts("BIND SOCK ERROR:"); }
//get data from client socket addr_len = sizeof client_soc_addr; numbytes = recvfrom(main_sock_fd, buf, MAXBUFLEN-1 , 0, (struct sockaddr *)&client_soc_addr, &addr_len); if (numbytes == -1) { puts("RECEIVE SOCK ERROR:"); } else { printf("got packet from %s\n",inet_ntoa(client_soc_addr.sin_addr)); printf("packet is %d bytes long\n",numbytes); buf[numbytes] = '\0'; printf("packet contains \"%s\"\n",buf); } //close and clean the sockets close_win_socket(main_sock_fd); clean_win_socket();
puts("any key to continue..."); getchar(); return 0; }
//this socket is intend to use as a simple client int main() { puts("start main client..."); int numBytes=0; int ret=0; char sendBuf[]="Hello, this is used to test UDP socket!\0";
//bind the socket ret = bind(local_sock_fd, (struct sockaddr *)&client_soc_addr, sizeof(client_soc_addr)); if(ret==-1) { puts("BIND SOCK ERROR:"); }
//configure the client's server socket addr main_soc_addr.sin_family = AF_INET; main_soc_addr.sin_port = htons(SERVERPORT); main_soc_addr.sin_addr.s_addr = inet_addr(SERVER_IP); memset(main_soc_addr.sin_zero, '\0', sizeof(main_soc_addr.sin_zero));
//now,we can send data to the server numBytes =sendto(local_sock_fd, sendBuf, strlen(sendBuf), 0, (struct sockaddr*)&main_soc_addr, sizeof(sockaddr)); if(numBytes ==-1) { puts("SEND DATA ERROR:"); }
//close and clean the windows sockets close_win_socket(local_sock_fd); clean_win_socket();
puts("any key to continue..."); getchar(); return 0; }