Nhull

Untitled

Apr 24th, 2016
649
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <sys/socket.h>
  7. #include <netinet/in.h>
  8.  
  9. void ErrorMessage(const char *msg){
  10.     perror(msg);
  11.     return;
  12. }
  13.  
  14. int main(int argc,char *argv[]){
  15.  
  16.     int sock_fd=0,new_sock_fd=0,port=0,clilen=0,n=0;
  17.     char buffer[256];
  18.     struct sockaddr_in serv_addr,cli_addr;
  19.  
  20.     if(argc<2){
  21.         fprintf(stderr,"Error port is missing\n");
  22.         return 0;
  23.     }
  24.  
  25.     sock_fd=socket(AF_INET,SOCK_STREAM,0);
  26.  
  27.     if(sock_fd<0)
  28.         fprintf(stderr,"Error opening socket");
  29.  
  30.     bzero((char *)&serv_addr,sizeof(serv_addr));
  31.     port=atoi(argv[1]);
  32.  
  33.     serv_addr.sin_family=AF_INET;
  34.     serv_addr.sin_port=htons(port);
  35.     serv_addr.sin_addr.s_addr=INADDR_ANY;
  36.  
  37.     if(bind(sock_fd, (struct sockaddr *) &serv_addr,sizeof(serv_addr))<0)
  38.         ErrorMessage("Error in connection");
  39.  
  40.     listen(sock_fd,5);
  41.  
  42.     clilen=sizeof(cli_addr);
  43.     new_sock_fd=accept(sock_fd,(struct sockaddr *)&cli_addr,&clilen);
  44.     if(new_sock_fd<0)
  45.         ErrorMessage("Error on accept");
  46.  
  47.     bzero(buffer,256);
  48.     n=read(new_sock_fd,buffer,255);
  49.  
  50.     if(n<0)
  51.         ErrorMessage("Error reading socket");
  52.     printf("Here is the message:%s",buffer);
  53.  
  54.     n=write(new_sock_fd,"Got your message",16);
  55.  
  56.     if(n<0)
  57.         ErrorMessage("Error writing on socket");
  58.     return 0;
  59. }
RAW Paste Data