SHARE
TWEET

server

a guest Oct 13th, 2019 83 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <WS2tcpip.h>
  3.  
  4. #pragma comment (lib, "ws2_32.lib")
  5.  
  6. void serverUDP()
  7. {
  8.     //Uruchomienie Winsocku
  9.     WSADATA data;
  10.     WORD version = MAKEWORD(2, 2);
  11.     int ws0k = WSAStartup(version, &data);
  12.     if (ws0k != 0)
  13.     {
  14.         std::cout << "Nie mozna uruchomic Winsocku!" << ws0k << "\n";
  15.     }
  16.     //Podlaczenie wejsc pod adres ip i porty
  17.     SOCKET in = socket(AF_INET, SOCK_DGRAM, 0);
  18.     sockaddr_in serverHint;
  19.     serverHint.sin_addr.S_un.S_addr = ADDR_ANY;
  20.     serverHint.sin_family = AF_INET;
  21.     serverHint.sin_port = htons(54000); //konwersja z little do big endian
  22.  
  23.     if (bind(in, (sockaddr*)& serverHint, sizeof(serverHint)) == SOCKET_ERROR)
  24.     {
  25.         std::cout << "Can't bind socket! " << WSAGetLastError() << '\n';
  26.         return;
  27.     }
  28.  
  29.     sockaddr_in client;
  30.     int clientLength = sizeof(client);
  31.  
  32.     char buf[1024];
  33.  
  34.     while (true)
  35.     {
  36.         ZeroMemory(&client, clientLength); //czyszczenie struktury klienta
  37.         ZeroMemory(buf, 1024); //czyszczenie bufera
  38.         std::cout << "dGddgFD\n";
  39.         //czekanie na wiadomosc
  40.         int bytesIn = recvfrom(in, buf, 1024, 0, (sockaddr*)& client, &clientLength);
  41.         if (bytesIn == SOCKET_ERROR)
  42.         {
  43.             std::cout << "Error receiving from client " << WSAGetLastError() << '\n';
  44.             continue;
  45.         }
  46.  
  47.         //wyswietlenie wiadomosci i informacji klienta
  48.         char clientIp[256]; //tworzenie obszaru do konwersji adresu
  49.         ZeroMemory(clientIp, 256);
  50.  
  51.         //konwersja z array do chars
  52.         inet_ntop(AF_INET, &client.sin_addr, clientIp, 256);
  53.  
  54.         //wyswietlenie wiadomosci/kto ja wyslal
  55.         std::cout << "Message recv from " << clientIp << " : " << buf << '\n';
  56.     }
  57.  
  58.     //zamkniecie polaczenia
  59.     closesocket(in);
  60.     WSACleanup();
  61. }
  62.  
  63. int main()
  64. {
  65.     serverUDP();
  66.     return 0;
  67. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top