This is sample code for UDP Server and Client Communication in C++.
Things to keep in mind :
Things to keep in mind :
- First Run server and then client
- If you receive error 10054 while running client, it is because of recvfrom() in client.cpp , as it is trying to receive from null reference. Either comment out recvfrom() or start server first.
//============================================================================ // Name : Simple C++ UDP Server.cpp // Author : Manish Kumar Khedawat //============================================================================ #include "stdafx.h" #include <iostream> #include <winsock2.h> #include<stdio.h> #define BUFLEN 512 #pragma comment(lib,"ws2_32.lib") //Winsock Library, To Avoid Error in Visual Studio Compilation using namespace std; int main() { WSAData version; //WSAData is Structure which holds the information about windows socket implementation WORD mkword=MAKEWORD(2,2); // MakeWord will return 2.2 int what=WSAStartup(mkword,&version); // Checking If you are on XP or Higher if(what!=0){ std::cout<<"This version is not supported! - \n"<<WSAGetLastError()<<std::endl; exit(EXIT_FAILURE); } else{ std::cout<<"Everything is fine!\n"<<std::endl; // Using XP+ } // Creating Socket SOCKET server=socket(AF_INET,SOCK_DGRAM,0); // (specify to use ipv4, Using UDP Port, Internet Protocol default 0 ) if(server==INVALID_SOCKET) { std::cout<<"Creating socket fail\n"; exit(EXIT_FAILURE); } else std::cout<<"Socket was created :)\n"; //Socket address information sockaddr_in ServerAddr; /* struct sockaddr_in { short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; }; */ ServerAddr.sin_family=AF_INET; // ipv4 specification ServerAddr.sin_addr.s_addr=inet_addr("127.0.0.1"); //ipAddress to bind server ServerAddr.sin_port=htons(8080); // port to bind /*==========Addressing finished==========*/ //Now we bind int conn=bind(server ,(struct sockaddr *)&ServerAddr , sizeof(ServerAddr)); if(conn==SOCKET_ERROR){ std::cout<<"Error - when connecting "<<WSAGetLastError()<<std::endl; closesocket(server); WSACleanup(); exit(EXIT_FAILURE); } else { std::cout<<"Socket bind Successful at " << inet_ntoa(ServerAddr.sin_addr) << ":"<<ntohs( ServerAddr.sin_port)<<std::endl; } while(1) { printf("Waiting for data...\n"); fflush(stdout); char buf[BUFLEN]; //clear the buffer by filling null, it might have previously received data memset(buf,'\0', BUFLEN); sockaddr_in client; int recv_len,client_len=sizeof(client); //try to receive some data, this is a blocking call if ((recv_len = recvfrom(server, buf, BUFLEN, 0, (struct sockaddr *)&client, &client_len)) == SOCKET_ERROR) { printf("recvfrom() failed with error code : %d\n" , WSAGetLastError()); exit(EXIT_FAILURE); } //print details of the client/peer and the data received printf("Received packet from client at %s\n", inet_ntoa(client.sin_addr)); printf("Data: %s\n" , buf); //now reply the client with the same data if (sendto(server, buf, recv_len, 0, (struct sockaddr*) &client, client_len) == SOCKET_ERROR) { printf("sendto() failed with error code : %d" , WSAGetLastError()); exit(EXIT_FAILURE); } } closesocket(server); WSACleanup(); return 0; }
//============================================================================ // Name : Simple C++ UDPClient.cpp // Author : Manish Kumar Khedawat //============================================================================ #include "stdafx.h" #include <iostream> #include <winsock2.h> #include<stdio.h> #pragma comment(lib,"ws2_32.lib") //Winsock Library, To Avoid Error in Visual Studio Compilation using namespace std; #define SERVER "127.0.0.1" //ip address of udp server #define BUFLEN 512 //Max length of buffer #define PORT 8080 //The port on which to listen for incoming data int main() { WSAData version; //WSAData is Structure which holds the information about windows socket implementation WORD mkword=MAKEWORD(2,2); // MakeWord will return 2.2 int what=WSAStartup(mkword,&version); // Checking If you are on XP or Higher if(what!=0){ std::cout<<"This version is not supported! - \n"<<WSAGetLastError()<<std::endl; exit(EXIT_FAILURE); } else{ std::cout<<"Everything is fine!\n"<<std::endl; // Using XP+ } // Creating Socket SOCKET client=socket(AF_INET,SOCK_DGRAM,0); // (specify to use ipv4, Using UDP Port, Internet Protocol default 0 ) if(client==INVALID_SOCKET) { std::cout<<"Creating socket fail\n"; exit(EXIT_FAILURE); } else std::cout<<"Socket was created :)\n"; //setup Server Address structure sockaddr_in server; memset((char *) &server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr.S_un.S_addr = inet_addr(SERVER); //start communication while(1) { char message[BUFLEN],buf[BUFLEN]; memset(message,'\0', BUFLEN); printf("Enter message : "); gets(message); int recv_len,server_len=sizeof(server); //send the message if (sendto(client, message, strlen(message) , 0 , (struct sockaddr *) &server, server_len) == SOCKET_ERROR) { printf("sendto() failed with error code : %d" , WSAGetLastError()); exit(EXIT_FAILURE); } //receive a reply and print it //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 (recvfrom(client, buf, BUFLEN, 0, (struct sockaddr *) &server, &server_len) == SOCKET_ERROR) { printf("recvfrom() failed with error code : %d" , WSAGetLastError()); exit(EXIT_FAILURE); } puts(buf); } closesocket(client); WSACleanup(); return 0; return 0; }
Comments
Post a Comment