/* UDP ServerSide Console App */ /* Bill Tompkins 4/2012 */ /* Use code at your own risk */ #include "stdafx.h" #include #include #include //#include #pragma comment(lib,"ws2_32.lib") //Windows Socket Library #define BUFLEN 512 //Max length of buffer #define PORT 8887 //The port on which to listen for incoming data int main() { SOCKET s; struct sockaddr_in server, si_other; int slen , recv_len; char buf[BUFLEN]; WSADATA wsa; slen = sizeof(si_other) ; //Initialize winsock printf("\nUDP Text Demo (ServerSide)"); printf("\nInitializing Winsock..."); if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) { printf("Failed. Error Code : %d",WSAGetLastError()); exit(EXIT_FAILURE); } printf("\nInitialized.\n"); //Create a socket if((s = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET) { printf("Socket Routine Failed. Error Code: %d" , WSAGetLastError()); } printf("\nSocket created.\n"); //Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( PORT ); //Bind if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR) { printf("\nBind Failed. Error Code: %d" , WSAGetLastError()); exit(EXIT_FAILURE); } puts("\nBind Successful"); //keep listening for data while(1) { printf("\nWaiting for Data..."); fflush(stdout); //clear the buffer by filling null, it might have previously received data memset(buf,'\0', BUFLEN); //try to receive some data, this is a blocking call if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == SOCKET_ERROR) { printf("Recvfrom Routine Failed. Error Code: %d" , WSAGetLastError()); exit(EXIT_FAILURE); } //print details of the client/peer and the data received printf("\n"); printf("Received Packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port)); printf("Data: %s\n" , buf); printf("Length: %d\n" , strlen(buf)); //now reply the client with the same data if (sendto(s, buf, recv_len, 0, (struct sockaddr*) &si_other, slen) == SOCKET_ERROR) { printf("Sendto Routine Failed. Error Code: %d" , WSAGetLastError()); exit(EXIT_FAILURE); } } closesocket(s); WSACleanup(); return 0; }