Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <netinet/in.h>
  5. #include <netdb.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <unistd.h>
  9.  
  10. void error(char *msg)
  11. {
  12. perror(msg);
  13. exit(0);
  14. }
  15.  
  16. int main(int argc, char *argv[])
  17. {
  18. int sockfd, portno, n;
  19.  
  20. struct sockaddr_in serv_addr;
  21. struct hostent *server;
  22.  
  23. char buffer[256];
  24. if (argc < 3) {
  25. fprintf(stderr,"usage %s hostname port\n", argv[0]);
  26. exit(0);
  27. }
  28. portno = atoi(argv[2]);
  29. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  30. if (sockfd < 0)
  31. error("ERROR opening socket");
  32. server = gethostbyname(argv[1]);
  33. if (server == NULL) {
  34. fprintf(stderr,"ERROR, no such host\n");
  35. exit(0);
  36. }
  37. bzero((char *) &serv_addr, sizeof(serv_addr));
  38. serv_addr.sin_family = AF_INET;
  39. bcopy((char *)server->h_addr,
  40. (char *)&serv_addr.sin_addr.s_addr,
  41. server->h_length);
  42. serv_addr.sin_port = htons(portno);
  43. if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
  44. error("ERROR connecting");
  45. printf("Please enter the message: ");
  46. bzero(buffer,256);
  47. fgets(buffer,255,stdin);
  48. n = write(sockfd,buffer,strlen(buffer));
  49. if (n < 0)
  50. error("ERROR writing to socket");
  51. bzero(buffer,256);
  52. n = read(sockfd,buffer,255);
  53. if (n < 0)
  54. error("ERROR reading from socket");
  55. printf("%s\n",buffer);
  56. return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement