Advertisement
farum12

Untitled

Aug 16th, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. #include <cstdio>
  2. #include<stdio.h>
  3. #include <WinSock2.h>
  4.  
  5. #pragma comment(lib,"ws2_32.lib") //Winsock Library
  6.  
  7. #define SERVER "127.0.0.1"  //ip address of udp server
  8. #define BUFLEN 512  //Max length of buffer
  9. #define PORT 11000   //The port on which to listen for incoming data
  10.  
  11. using namespace std;
  12.  
  13. int main(void)
  14. {
  15.     struct sockaddr_in si_other;
  16.     int s, slen = sizeof(si_other);
  17.     char buf[BUFLEN];
  18.     char message[BUFLEN];
  19.     WSAData wsa;
  20.     WORD DllVersion = MAKEWORD(2, 2);
  21.  
  22.     //Initialise winsock
  23.     printf("\nInitialising Winsock...");
  24.     if ((DllVersion, &wsa) != 0)
  25.     {
  26.         printf("Failed. Error Code : %d", WSAGetLastError());
  27.         exit(EXIT_FAILURE);
  28.     }
  29.     printf("Initialised.\n");
  30.  
  31.     //create socket
  32.     if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
  33.     {
  34.         printf("socket() failed with error code : %d", WSAGetLastError());
  35.         exit(EXIT_FAILURE);
  36.     }
  37.  
  38.     //setup address structure
  39.     memset((char *)&si_other, 0, sizeof(si_other));
  40.     si_other.sin_family = AF_INET;
  41.     si_other.sin_port = htons(PORT);
  42.     si_other.sin_addr.S_un.S_addr = inet_addr(SERVER);
  43.  
  44.     //start communication
  45.     while (1)
  46.     {
  47.         printf("Enter message : ");
  48.         gets(message);
  49.  
  50.         //send the message
  51.         if (sendto(s, message, strlen(message), 0, (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
  52.         {
  53.             printf("sendto() failed with error code : %d", WSAGetLastError());
  54.             exit(EXIT_FAILURE);
  55.         }
  56.  
  57.         //receive a reply and print it
  58.         //clear the buffer by filling null, it might have previously received data
  59.         memset(buf, '\0', BUFLEN);
  60.         //try to receive some data, this is a blocking call
  61.         if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == SOCKET_ERROR)
  62.         {
  63.             printf("recvfrom() failed with error code : %d", WSAGetLastError());
  64.             exit(EXIT_FAILURE);
  65.         }
  66.  
  67.         puts(buf);
  68.     }
  69.  
  70.     closesocket(s);
  71.     WSACleanup();
  72.  
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement