Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.71 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <sys/socket.h>
  4. #include <stdlib.h>
  5. #include <netinet/in.h>
  6. #include <string.h>
  7. #define PORT 8080
  8. int main(int argc, char const *argv[])
  9. {
  10.     int server_fd, new_socket, valread;
  11.     struct sockaddr_in address;
  12.     int opt = 1;
  13.     int addrlen = sizeof(address);
  14.     char buffer[1024] = {0};
  15.     char *hello = "Hello from server";
  16.        
  17.     // Creating socket file descriptor
  18.     if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
  19.     {
  20.         perror("socket failed");
  21.         exit(EXIT_FAILURE);
  22.     }
  23.        
  24.     // Forcefully attaching socket to the port 8080
  25.     if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
  26.                                                   &opt, sizeof(opt)))
  27.     {
  28.         perror("setsockopt");
  29.         exit(EXIT_FAILURE);
  30.     }
  31.     address.sin_family = AF_INET;
  32.     address.sin_addr.s_addr = INADDR_ANY;
  33.     address.sin_port = htons( PORT );
  34.        
  35.     // Forcefully attaching socket to the port 8080
  36.     if (bind(server_fd, (struct sockaddr *)&address,  
  37.                                  sizeof(address))<0)
  38.     {
  39.         perror("bind failed");
  40.         exit(EXIT_FAILURE);
  41.     }
  42.     if (listen(server_fd, 3) < 0)
  43.     {
  44.         perror("listen");
  45.         exit(EXIT_FAILURE);
  46.     }
  47.     if ((new_socket = accept(server_fd, (struct sockaddr *)&address,  
  48.                        (socklen_t*)&addrlen))<0)
  49.     {
  50.         perror("accept");
  51.         exit(EXIT_FAILURE);
  52.     }
  53.     valread = read( new_socket , buffer, 1024);
  54.     printf("%s\n",buffer );
  55.     send(new_socket , hello , strlen(hello) , 0 );
  56.     printf("Hello message sent\n");
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement