Advertisement
Guest User

Untitled

a guest
Nov 17th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/socket.h>
  5. #include <sys/types.h>
  6. #include <netinet/in.h>
  7. #include <arpa/inet.h>
  8.  
  9. #define MAX_MSG_LEN 4096
  10. #define SERWER_PORT 8888
  11. #define SERWER_IP "127.0.0.1"
  12. #define MAX_CONNECTION 10
  13.  
  14.  
  15. int main()
  16. {
  17. struct sockaddr_in serwer =
  18. {
  19. .sin_family = AF_INET,
  20. .sin_port = htons( SERWER_PORT )
  21. };
  22. if( inet_pton( AF_INET, SERWER_IP, & serwer.sin_addr ) <= 0 )
  23. {
  24. perror( "inet_pton() ERROR" );
  25. exit( 1 );
  26. }
  27.  
  28. const int socket_ = socket( AF_INET, SOCK_STREAM, 0 );
  29. if( socket_ < 0 )
  30. {
  31. perror( "socket() ERROR" );
  32. exit( 2 );
  33. }
  34.  
  35. socklen_t len = sizeof( serwer );
  36. if( bind( socket_,( struct sockaddr * ) & serwer, len ) < 0 )
  37. {
  38. perror( "bind() ERROR" );
  39. exit( 3 );
  40. }
  41.  
  42. if( listen( socket_, MAX_CONNECTION ) < 0 )
  43. {
  44. perror( "listen() ERROR" );
  45. exit( 4 );
  46. }
  47.  
  48.  
  49. while( 1 )
  50. {
  51. printf( "Waiting for connection...\n" );
  52.  
  53. struct sockaddr_in client = { };
  54.  
  55. const int clientSocket = accept( socket_,( struct sockaddr * ) & client, & len );
  56. if( clientSocket < 0 )
  57. {
  58. perror( "accept() ERROR" );
  59. continue;
  60. }
  61.  
  62. char buffer[ MAX_MSG_LEN ] = { };
  63.  
  64. if( recv( clientSocket, buffer, sizeof( buffer ), 0 ) <= 0 )
  65. {
  66. perror( "recv() ERROR" );
  67. exit( 5 );
  68. }
  69. printf( "|Message from client|: %s \n", buffer );
  70.  
  71. strcpy( buffer, "Message from server" );
  72. if( send( clientSocket, buffer, strlen( buffer ), 0 ) <= 0 )
  73. {
  74. perror( "send() ERROR" );
  75. exit( 6 );
  76. }
  77.  
  78. shutdown( clientSocket, SHUT_RDWR );
  79. }
  80.  
  81. shutdown( socket_, SHUT_RDWR );
  82. }
  83. // gcc server.c -g -Wall -o server && ./server
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement