halfordC

C Class SocketServer

Sep 28th, 2020
1,256
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <sys/socket.h>
  3. #include <sys/types.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.   perror(msg);
  13.   exit(0);
  14. }
  15.  
  16. int main(int argc, char *argv[])
  17. {
  18.   int sockfd, portno, n;
  19.   struct sockaddr_in serv_addr;
  20.   struct hostent *server;
  21.   char buffer[256];
  22.   if (argc<3)
  23.   {
  24.     fprintf(stderr, "usage %s hostname port\n", argv[0]);
  25.     exit(0);
  26.   }
  27.   portno = atoi(argv[2]);
  28.   sockfd = socket(AF_INET, SOCK_STREAM,0);
  29.   if(server == NULL)
  30.   {
  31.     fprintf(stderr,"ERROR, no such host\n");
  32.     exit(0);
  33.   }
  34.   bzero((char*)&serv_addr, sizeof(serv_addr));
  35.   serv_addr.sin_family = AF_INET;
  36.   if(connect(sockfd,(struct sockaddr *) &serv_addr, sizeof(serv_addr))<0)
  37.   {
  38.     error("ERROR connecting");
  39.   }
  40.   printf("Please enter the mesage: ");
  41.   bzero(buffer, 256);
  42.   fgets(buffer, 255, stdin);
  43.   n= write(sockfd,buffer,strlen(buffer));
  44.   if(n<0)
  45.   {
  46.     error("ERROR writing to socket");
  47.   }
  48. bzero(buffer,256);
  49.   n=read(sockfd,buffer,255);
  50.   if (n<0)
  51.   {
  52.     error("Error reading from socket");
  53.   }
  54.   printf("%s\n", buffer);
  55. return 0;
  56.  
  57. }
  58.  
  59.  
RAW Paste Data