Untitled

By Gentle Madrill, 2 Weeks ago, written in c.
  1. /*
  2. **client.c-astreamsocketclientdemo
  3. */
  4.  
  5. #include<stdio.h>
  6. #include<stdlib.h>
  7. #include<unistd.h>
  8. #include<errno.h>
  9. #include<string.h>
  10. #include<netdb.h>
  11. #include<sys/types.h>
  12. #include<netinet/in.h>
  13. #include<sys/socket.h>
  14.  
  15. #define PORT3490                        //theportclientwillbeconnectingto
  16. #define MAXDATASIZE100                  //maxnumberofbyteswecangetatonce
  17.  
  18. int main(intargc,char*argv[])
  19. {
  20. int sockfd, numbytes;
  21. char buf[ MAXDATASIZE ];
  22. struct hostent *he;
  23. struct sockaddr_in their_addr;          //connector’saddressinformation
  24.  
  25. if(argc != 2)
  26. {
  27.         fprintf( stderr, "usage: client hostname\n");
  28.         exit(1);
  29. }
  30.  
  31. if(( he = gethostbyname( argv[1]) ) == NULL)   //getthehostinfo
  32. {
  33.         perror("gethostbyname");
  34.         exit(1);
  35. }
  36.  
  37. if(( sockfd = socket( AF_INET, SOCK_STREAM, 0)) == -1)
  38. {
  39.         perror("socket");
  40.         exit(1);
  41. }
  42. their_addr.sin_family = AF_INET;             //hostbyteorder
  43. their_addr.sin_port = htons( PORT );         //short,networkbyteorder
  44. their_addr.sin_addr = *(( structin_addr *)he->h_addr);
  45. memset(&( their_addr.sin_zero ), ’\0’, 8);   //zerotherestofthestruct
  46.  
  47. if( connect( sockfd,( structsockaddr *) &their_addr, sizeof( structsockaddr )) == -1 )
  48. {
  49.         perror("connect");
  50.         exit(1);
  51. }
  52.  
  53. if(( numbytes = recv( sockfd, buf, MAXDATASIZE -1, 0 )) == -1)
  54. {
  55.         perror("recv");
  56.         exit(1);
  57. }
  58. buf[numbytes] = ’\0’;
  59. printf( "Received:%s",buf );
  60. close( sockfd );
  61. return 0;
  62. }