Advertisement
zaxisss

Untitled

Mar 14th, 2022
634
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <sys/socket.h>
  2. #include <sys/types.h>
  3. #include <netinet/in.h>
  4. #include <stdio.h>
  5. #define SERV_PORT 45000
  6. #define BUFOR 100
  7. int main()
  8. {
  9.     int listenfd;
  10.     int connfd;
  11.     pid_t child;
  12.     socklen_t klient_len;
  13.     struct sockaddr_in klient_addres, serwer_addres;
  14.     char Addr[100];
  15.     int ChId;
  16.     listenfd = socket(AF_INET, SOCK_STREAM, 0);
  17.     bzero(&serwer_addres, sizeof(serwer_addres));
  18.     serwer_addres.sin_family = AF_INET;
  19.     serwer_addres.sin_addr.s_addr = htonl(INADDR_ANY);
  20.     serwer_addres.sin_port = htons(SERV_PORT);
  21.     bind(listenfd, &serwer_addres, sizeof(serwer_addres));
  22.     listen(listenfd, BUFOR);
  23.     inet_ntop(AF_INET, &serwer_addres.sin_addr, Addr, 100);
  24.     printf("\nSERWER: Serwer zostal uruchomiony IP=%s,%d", Addr, SERV_PORT);
  25.     for (;;)
  26.     {
  27.         klient_len = sizeof(klient_addres);
  28.         connfd = accept(listenfd, &klient_addres, &klient_len);
  29.         if (fork() == 0)
  30.         {
  31.             ChId = getpid();
  32.             printf("%d", ChId);
  33.             close(listenfd);
  34.             inet_ntop(AF_INET, &klient_addres.sin_addr, Addr, 100);
  35.             printf("\nSERWER(%ld): Polaczenie klienta z komputerem o adresie IP=%s", ChId, Addr);
  36.             Echo(connfd);
  37.             printf("\nSERWER(%ld): Obsluga klienta o adresie IP=%s zostala zakonczona", ChId, Addr);
  38.             close(connfd);
  39.             exit(0);
  40.         }
  41.         close(connfd);
  42.     }
  43. }
  44. void Echo(int socketfd)
  45. {
  46.     int n;
  47.     char bufor[100];
  48.     char line[100];
  49.     for (;;)
  50.     {
  51.         n = read(socketfd, line, 100); // n=strlen (1ine);
  52.         // n=Czytaj( socket, line, 100);
  53.         if (n <= 1)
  54.         {
  55.             printf("\nSERWER: POLACZENIE ZAKONCZONO ");
  56.             return;
  57.         }
  58.  
  59.         line[n] = '\0';
  60.         printf("\nSERWER: ODEBRANO %d znakow--> %s ", n, line);
  61.         write(socketfd, line, n);
  62.         printf("\nSERWER: WYSLANO --> %s", line);
  63.     } // for
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement