Guest User

C Client for stream socket

a guest
Oct 8th, 2016
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. /*
  2. ** client.c -- a stream socket client demo
  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. #include <arpa/inet.h>
  16.  
  17. #define PORT "10012" // the port client will be connecting to
  18.  
  19. #define MAXDATASIZE 100 // max number of bytes we can get at once
  20.  
  21. // get sockaddr, IPv4 or IPv6:
  22. void *get_in_addr(struct sockaddr *sa)
  23. {
  24. if (sa->sa_family == AF_INET) {
  25. return &(((struct sockaddr_in*)sa)->sin_addr);
  26. }
  27.  
  28. return &(((struct sockaddr_in6*)sa)->sin6_addr);
  29. }
  30.  
  31. int main(int argc, char *argv[])
  32. {
  33. int sockfd, numbytes;
  34. char buf[MAXDATASIZE];
  35. struct addrinfo hints, *servinfo, *p;
  36. int rv;
  37. char s[INET6_ADDRSTRLEN];
  38.  
  39. if (argc != 2) {
  40. fprintf(stderr,"usage: client hostname\n");
  41. exit(1);
  42. }
  43.  
  44. memset(&hints, 0, sizeof hints);
  45. hints.ai_family = AF_UNSPEC;
  46. hints.ai_socktype = SOCK_STREAM;
  47.  
  48. if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) {
  49. fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
  50. return 1;
  51. }
  52.  
  53. // loop through all the results and connect to the first we can
  54. for(p = servinfo; p != NULL; p = p->ai_next) {
  55. if ((sockfd = socket(p->ai_family, p->ai_socktype,
  56. p->ai_protocol)) == -1) {
  57. perror("client: socket");
  58. continue;
  59. }
  60.  
  61. if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
  62. close(sockfd);
  63. perror("client: connect");
  64. continue;
  65. }
  66.  
  67. break;
  68. }
  69.  
  70. if (p == NULL) {
  71. fprintf(stderr, "client: failed to connect\n");
  72. return 2;
  73. }
  74.  
  75. inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
  76. s, sizeof s);
  77. printf("client: connecting to %s\n", s);
  78.  
  79. freeaddrinfo(servinfo); // all done with this structure
  80.  
  81. if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
  82. perror("recv");
  83. exit(1);
  84. }
  85.  
  86. buf[numbytes] = '\0';
  87.  
  88. printf("client: received '%s'\n",buf);
  89.  
  90. close(sockfd);
  91.  
  92. return 0;
  93. }
Add Comment
Please, Sign In to add comment