Mihailo21

ServerUDPPostavka1

Nov 20th, 2023
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 4.34 KB | None | 0 0
  1. // UDP server that use blocking sockets
  2. #define _WINSOCK_DEPRECATED_NO_WARNINGS
  3.  
  4. #define WIN32_LEAN_AND_MEAN
  5.  
  6. #include <windows.h>
  7. #include <winsock2.h>
  8. #include <ws2tcpip.h>
  9. #include <stdlib.h>
  10. #include <stdio.h>
  11. #include "conio.h"
  12.  
  13. #pragma comment (lib, "Ws2_32.lib")
  14. #pragma comment (lib, "Mswsock.lib")
  15. #pragma comment (lib, "AdvApi32.lib")
  16.  
  17. #define SERVER_PORT 15000   // Port number of server that will be used for communication with clients
  18. #define BUFFER_SIZE 512     // Size of buffer that will be used for sending and receiving messages to clients
  19.  
  20. int main()
  21. {
  22.     // Server address
  23.     sockaddr_in serverAddress;
  24.  
  25.     // Buffer we will use to send and receive clients' messages
  26.     char dataBuffer[BUFFER_SIZE];
  27.  
  28.     // WSADATA data structure that is to receive details of the Windows Sockets implementation
  29.     WSADATA wsaData;
  30.  
  31.     // Initialize windows sockets library for this process
  32.     if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
  33.     {
  34.         printf("WSAStartup failed with error: %d\n", WSAGetLastError());
  35.         return 1;
  36.     }
  37.  
  38.     // Initialize serverAddress structure used by bind function
  39.     memset((char*)&serverAddress, 0, sizeof(serverAddress));
  40.     serverAddress.sin_family = AF_INET;             // set server address protocol family
  41.     serverAddress.sin_addr.s_addr = INADDR_ANY;     // use all available addresses of server
  42.     serverAddress.sin_port = htons(SERVER_PORT);
  43.  
  44.     // Create a socket
  45.     SOCKET serverSocket = socket(AF_INET,      // IPv4 address famly
  46.         SOCK_DGRAM,                            // datagram socket
  47.         IPPROTO_UDP);                          // UDP
  48.  
  49.     // Check if socket creation succeeded
  50.     if (serverSocket == INVALID_SOCKET)
  51.     {
  52.         printf("Creating socket failed with error: %d\n", WSAGetLastError());
  53.         WSACleanup();
  54.         return 1;
  55.     }
  56.  
  57.     // Bind server address structure (type, port number and local address) to socket
  58.     int iResult = bind(serverSocket, (SOCKADDR*)&serverAddress, sizeof(serverAddress));
  59.  
  60.     // Check if socket is succesfully binded to server datas
  61.     if (iResult == SOCKET_ERROR)
  62.     {
  63.         printf("Socket bind failed with error: %d\n", WSAGetLastError());
  64.         closesocket(serverSocket);
  65.         WSACleanup();
  66.         return 1;
  67.     }
  68.  
  69.     printf("Simple UDP server started and waiting client messages.\n");
  70.  
  71.     // Main server loop
  72.     while (1)
  73.     {
  74.         // Declare and initialize client address that will be set from recvfrom
  75.         sockaddr_in clientAddress;
  76.         memset(&clientAddress, 0, sizeof(clientAddress));
  77.  
  78.         // Set whole buffer to zero
  79.         memset(dataBuffer, 0, BUFFER_SIZE);
  80.  
  81.         // size of client address
  82.         int sockAddrLen = sizeof(clientAddress);
  83.  
  84.         // Receive client message
  85.         iResult = recvfrom(serverSocket,    // Own socket
  86.             dataBuffer,                     // Buffer that will be used for receiving message
  87.             BUFFER_SIZE,                    // Maximal size of buffer
  88.             0,                              // No flags
  89.             (SOCKADDR*)&clientAddress,      // Client information from received message (ip address and port)
  90.             &sockAddrLen);                  // Size of sockadd_in structure
  91.  
  92.         // Check if message is succesfully received
  93.         if (iResult == SOCKET_ERROR)
  94.         {
  95.             printf("recvfrom failed with error: %d\n", WSAGetLastError());
  96.             continue;
  97.         }
  98.  
  99.         // Set end of string
  100.         dataBuffer[iResult] = '\0';
  101.  
  102.         char ipAddress[16]; // 15 spaces for decimal notation (for example: "192.168.100.200") + '\0'
  103.  
  104.         // Copy client ip to local char[]
  105.         strcpy_s(ipAddress, sizeof(ipAddress), inet_ntoa(clientAddress.sin_addr));
  106.  
  107.         // Convert port number from network byte order to host byte order
  108.         unsigned short clientPort = ntohs(clientAddress.sin_port);
  109.  
  110.         printf("Client connected from ip: %s, port: %d, sent: %s.\n", ipAddress, clientPort, dataBuffer);
  111.  
  112.         // Possible server-shutdown logic could be put here
  113.     }
  114.  
  115.     // Close server application
  116.     iResult = closesocket(serverSocket);
  117.     if (iResult == SOCKET_ERROR)
  118.     {
  119.         printf("closesocket failed with error: %ld\n", WSAGetLastError());
  120.         WSACleanup();
  121.         return 1;
  122.     }
  123.  
  124.     printf("Server successfully shut down.\n");
  125.  
  126.     // Close Winsock library
  127.     WSACleanup();
  128.  
  129.     return 0;
  130. }
Add Comment
Please, Sign In to add comment