Advertisement
halfordC

C Class SocketServerServer

Sep 28th, 2020
1,421
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <netinet/in.h>
  5. #include <netdb.h>
  6. #include <unistd.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9.  
  10. void error(char *msg)
  11. {
  12.   //peror(msg); //c11
  13.   //exit(1);
  14.  
  15. }
  16.  
  17. int main(int argc, char *argv[]) {
  18.   //initializing all empty variables, structs, and array
  19.   int sockfd, newsockfd, portno, clilen, n;
  20.   char buffer[256];
  21.   struct sockaddr_in serv_addr, cli_addr;
  22.  
  23.   if(argc < 2)
  24.   {
  25.     fprintf(stderr,"Error, no port provided\n");
  26.     //exit(1);
  27.   }
  28.   sockfd = socket(AF_INET, SOCK_STREAM,0);
  29.   if(sockfd < 0)
  30.   {
  31.     error("Error opening socket");
  32.   }
  33.   //bzero((char *) &serv_addr,sizeof(serv_addr)); //this may not be necessary //c11
  34.   portno = atoi(argv[1]);
  35.   serv_addr.sin_family = AF_INET;
  36.   serv_addr.sin_port = htons(portno);
  37.   serv_addr.sin_addr.s_addr = INADDR_ANY;
  38.  
  39.   if(bind(sockfd,(struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0)
  40.       {
  41.         error("Error on binding");
  42.       }
  43.   listen(sockfd,5);
  44.   clilen = sizeof(cli_addr);
  45.   newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
  46.   if (newsockfd < 0)
  47.  {
  48.     error("ERROR on accept");
  49.   }
  50.   bzero(buffer,256);
  51.   n = read(newsockfd,buffer,255);
  52.  
  53.   if(n < 0)
  54.   {
  55.     error("Error reading from socket");
  56.   }
  57.  
  58.   printf("Here is the message: %s\n", buffer);
  59.  
  60.   n = write(newsockfd, "I got your message", 18);
  61.   if(n<0)
  62.   {
  63.     error("Error writing to socket");
  64.   }
  65.   return 0;
  66. }
  67.  
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement