Advertisement
seba101

(PWŚS) UDP - Klient

Mar 11th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1.  
  2. #include <stdio.h>
  3. #include "stdafx.h"
  4. #include <locale.h>
  5. #include <WinSock2.h>
  6. #include <conio.h>
  7.  
  8. #pragma comment(lib, "Ws2_32.lib")
  9.  
  10. void CheckErrorByCode(int code)
  11. {
  12.  
  13.     char Buff[1024];
  14.     FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, code, NULL, Buff, sizeof(Buff), NULL);
  15.     printf(" %s", Buff);
  16.  
  17. }
  18.  
  19. int main(int argc, char** argv) {
  20.     setlocale(LC_ALL, "Polish");
  21.  
  22.  
  23.     WSADATA wsa;
  24.     SOCKADDR_IN addr;
  25.     addr.sin_family = AF_INET;
  26.     addr.sin_port = htons(19390);
  27.     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
  28.     char BuffToSend[2048];
  29.     char BuffToShow[2048];
  30.     char Host[512];
  31.  
  32.     int result = WSAStartup(MAKEWORD(2, 0), &wsa);
  33.  
  34.     if (result != 1)
  35.     {
  36.         printf("WSAStartup initialization: ");
  37.         CheckErrorByCode(result);
  38.     }
  39.     else
  40.     {
  41.         printf("WSAStartup initialization error! Error code: %d", result);
  42.         CheckErrorByCode(result);
  43.     }
  44.  
  45.     result = gethostname(Host, sizeof(Host));
  46.  
  47.     if (result == 1)
  48.     {
  49.         printf("Get hostname function error! Error code: %d", result);
  50.         CheckErrorByCode(result);
  51.     }
  52.  
  53.     SOCKET Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  54.     bind(Socket, (SOCKADDR*)&addr, sizeof(addr));
  55.  
  56.  
  57.     for (int i = 0; i < 2048; i++)
  58.     {
  59.         BuffToSend[i] = NULL;
  60.         BuffToShow[i] = NULL;
  61.     }
  62.    
  63.  
  64.     printf("%s: ", Host);
  65.     scanf("%s", &BuffToSend);
  66.     sendto(Socket, BuffToSend, strlen(BuffToSend), 0, (SOCKADDR*)&addr, sizeof(addr));
  67.     int AddrSize = sizeof(addr);
  68.     recvfrom(Socket, BuffToShow, sizeof(BuffToShow), 0, (SOCKADDR*)&addr, &AddrSize);
  69.     printf("\nAnon: %s", BuffToShow);
  70.    
  71.     closesocket(Socket);
  72.     _getch();
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement