Advertisement
kator

tcp-server

Mar 21st, 2019
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.59 KB | None | 0 0
  1. /*
  2.  *
  3.  * Compilation:  gcc -Wall ./tcp-server.c -o ./tcp-server
  4.  * Usage:        ./tcp-server
  5.  *
  6.  *
  7.  */
  8.  
  9. #include <netinet/in.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <sys/socket.h>
  13. #include <unistd.h>
  14. #include <stdio.h>
  15. #include <netdb.h>
  16.  
  17. int main(int argc, char** argv) {
  18.     if (argc != 3) {
  19.         printf("usage: ./tcp-server <IP> <PORT>\n");
  20.         return -1;
  21.     }
  22.    
  23.   socklen_t sl;
  24.   int sfd, cfd, on = 1;
  25.   struct sockaddr_in saddr, caddr;
  26.  
  27.   memset(&saddr, 0, sizeof(saddr));
  28.   saddr.sin_family = AF_INET;
  29.   saddr.sin_addr.s_addr = INADDR_ANY;
  30.   saddr.sin_port = htons(1234);
  31.   sfd = socket(PF_INET, SOCK_STREAM, 0);
  32.   setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (char*) &on, sizeof(on));
  33.   bind(sfd, (struct sockaddr*) &saddr, sizeof(saddr));
  34.   listen(sfd, 5);
  35.  
  36.   unsigned long long int asdf = 0;
  37.  
  38.   while(1) {
  39.    
  40.     memset(&caddr, 0, sizeof(caddr));
  41.     sl = sizeof(caddr);
  42.     cfd = accept(sfd, (struct sockaddr*) &caddr, &sl);
  43.     char buff[256] = {0};
  44.     int sz = read(cfd, &buff, 256);
  45.     if (sz <= 0) {
  46.         printf("something went wrong!");
  47.     }
  48.  
  49.     printf("[got:]\t%s\n", buff);
  50.  
  51.     int csfd;
  52.     struct sockaddr_in csaddr;
  53.     struct hostent* caddrent;
  54.    
  55.     caddrent = gethostbyname(argv[1]);
  56.     csfd = socket(PF_INET, SOCK_STREAM, 0);
  57.     memset(&csaddr, 0, sizeof(csaddr));
  58.     csaddr.sin_family = AF_INET;
  59.     csaddr.sin_port = htons(atoi(argv[2]));
  60.     memcpy(&csaddr.sin_addr.s_addr, caddrent->h_addr, caddrent->h_length);
  61.     connect(csfd, (struct sockaddr*) &csaddr, sizeof(csaddr));
  62.     write(csfd, &buff, sz);
  63.     close(csfd);
  64.   }
  65.   close(sfd);
  66.   return EXIT_SUCCESS;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement