Advertisement
Guest User

Untitled

a guest
Jan 19th, 2020
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <errno.h>
  3. #include <netinet/in.h>
  4. #include <sys/socket.h>
  5. #include <cstdlib>
  6. #include <cstdio>
  7. #include <error.h>
  8.  
  9. const int one = 1;
  10.  
  11. int main(int argc, char ** argv){
  12.     if(argc!=2)
  13.         error(1,0,"Usage: %s <port>", argv[0]);
  14.    
  15.     sockaddr_in localAddress{
  16.         .sin_family = AF_INET,
  17.         .sin_port   = htons(atoi(argv[1])),
  18.         .sin_addr   = {htonl(INADDR_ANY)}
  19.     };
  20.    
  21.     int servSock = socket(PF_INET, SOCK_STREAM, 0);
  22.     setsockopt(servSock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
  23.    
  24.     if(bind(servSock, (sockaddr*) &localAddress, sizeof(localAddress)))
  25.         error(1,errno,"Bind failed!");
  26.    
  27.     listen(servSock, 1);
  28.  
  29.     while(true) {
  30.         int clientSock = accept(servSock, nullptr, nullptr);
  31.         printf("Accepted a new connection\n");
  32.         while(true){
  33.             char data[11]{};
  34.             int len = read(clientSock, data, sizeof(data)-1);
  35.             if(len<1) break;
  36.             printf(" Received %2d bytes: |%s|\n",len, data);
  37.         }
  38.         close(clientSock);
  39.         printf("Connection closed\n");
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement