Advertisement
thedarkfreak

Winsock 2 C Test - Client

Jan 21st, 2014
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.88 KB | None | 0 0
  1. // Winsock32Client.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #define WIN32_LEAN_AND_MEAN
  5. #include <Windows.h>
  6. #include <WinSock2.h>
  7. #include <ws2tcpip.h>
  8. #include <iphlpapi.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <tchar.h>
  12.  
  13. #pragma comment(lib, "Ws2_32.lib")
  14.  
  15. #define DEFAULT_PORT "27015"
  16. #define BUFSIZE 1024
  17.  
  18. int _tmain(int argc, _TCHAR* argv[])
  19. {
  20.     WSADATA wsaData;
  21.     int iResult;
  22.     TCHAR buf[BUFSIZE];
  23.     sockaddr_in remaddr;
  24.     socklen_t addrlen = sizeof(remaddr);
  25.     int recvlen;
  26.  
  27.     iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
  28.     if (iResult != 0){
  29.         printf("WSAStartup failed: %d\n", iResult);
  30.         return 1;
  31.     }
  32.  
  33.     struct addrinfo *result = NULL, *ptr = NULL, hints;
  34.  
  35.     ZeroMemory(&hints, sizeof(hints));
  36.     hints.ai_family = AF_INET;
  37.     hints.ai_socktype = SOCK_DGRAM;
  38.     hints.ai_protocol = IPPROTO_UDP;
  39.     hints.ai_flags = AI_PASSIVE;
  40.  
  41.     iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
  42.     if (iResult != 0) {
  43.         printf("getaddrinfo failed: %d\n", iResult);
  44.         WSACleanup();
  45.         return 1;
  46.     }
  47.  
  48.     SOCKET ListenSocket = INVALID_SOCKET;
  49.     ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
  50.  
  51.     if (ListenSocket == INVALID_SOCKET)
  52.     {
  53.         printf("Error at socket(): %ld\n", WSAGetLastError());
  54.         freeaddrinfo(result);
  55.         WSACleanup();
  56.         return 1;
  57.     }
  58.  
  59.  
  60.     TCHAR test[] = "END";
  61.     int sendlen = sendto(ListenSocket, test, strlen(test), 0, result->ai_addr, result->ai_addrlen);
  62.     printf("sent %d bytes\n", sendlen);
  63.     if (sendlen < 0)
  64.     {
  65.         printf("send error: %d\n", WSAGetLastError());
  66.     }
  67.  
  68.     recvlen = recvfrom(ListenSocket, buf, BUFSIZE, 0, (sockaddr *)&remaddr, &addrlen);
  69.     printf("received %d bytes\n", recvlen);
  70.     if (recvlen > 0){
  71.     buf[recvlen] = 0;
  72.     printf("received message: %s\n", buf);
  73.     }
  74.  
  75.     system("PAUSE");
  76.     freeaddrinfo(result);
  77.     closesocket(ListenSocket);
  78.     WSACleanup();
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement