Facebook
From MD Rashedul Hasan, 2 Weeks ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 185
  1. #include <stdio.h>
  2. #include <winsock2.h>
  3.  
  4. #pragma comment(lib, "ws2_32.lib")
  5.  
  6. int main() {
  7.     WSADATA wsaData;
  8.     SOCKET serverSocket, clientSocket;
  9.     struct sockaddr_in serverAddr, clientAddr;
  10.     int clientAddrLen = sizeof(clientAddr);
  11.     char buffer[1024];
  12.  
  13.     // Initialize Winsock
  14.     if (WSAStartup(MAKEWORD(2, 2), &wsaData;) != 0) {
  15.         fprintf(stderr, "Failed to initialize Winsockn");
  16.         return 1;
  17.     }
  18.  
  19.     // Create a socket
  20.     serverSocket = socket(AF_INET, SOCK_STREAM, 0);
  21.     if (serverSocket == INVALID_SOCKET) {
  22.         fprintf(stderr, "Failed to create socketn");
  23.         WSACleanup();
  24.         return 1;
  25.     }
  26.  
  27.     // Set up the server address structure
  28.     serverAddr.sin_family = AF_INET;
  29.     serverAddr.sin_addr.s_addr = INADDR_ANY;
  30.     serverAddr.sin_port = htons(8080);
  31.  
  32.     // Bind the socket
  33.     if (bind(serverSocket, (struct sockaddr*)&serverAddr;, sizeof(serverAddr)) == SOCKET_ERROR) {
  34.         fprintf(stderr, "Bind failedn");
  35.         closesocket(serverSocket);
  36.         WSACleanup();
  37.         return 1;
  38.     }
  39.  
  40.     // Listen for incoming connections
  41.     if (listen(serverSocket, 5) == SOCKET_ERROR) {
  42.         fprintf(stderr, "Listen failedn");
  43.         closesocket(serverSocket);
  44.         WSACleanup();
  45.         return 1;
  46.     }
  47.  
  48.     printf("Server listening on port 8080...n");
  49.  
  50.     // Accept incoming connections
  51.     clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr;, &clientAddrLen;);
  52.     if (clientSocket == INVALID_SOCKET) {
  53.         fprintf(stderr, "Accept failedn");
  54.         closesocket(serverSocket);
  55.         WSACleanup();
  56.         return 1;
  57.     }
  58.  
  59.     printf("Connection accepted from %sn", inet_ntoa(clientAddr.sin_addr));
  60.  
  61.     // Receive data from the client
  62.     int bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0);
  63.     if (bytesRead > 0) {
  64.         printf("Received data from client: %.*sn", bytesRead, buffer);
  65.     } else {
  66.         fprintf(stderr, "Error receiving datan");
  67.     }
  68.  
  69.     // Close sockets and clean up
  70.     closesocket(clientSocket);
  71.     closesocket(serverSocket);
  72.     WSACleanup();
  73.  
  74.     return 0;
  75. }
  76.