Advertisement
Guest User

Untitled

a guest
Sep 20th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. #include <cstring>
  2. #include <netdb.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <sys/socket.h>
  6. #include <sys/types.h>
  7. #include <unistd.h>
  8.  
  9. #define BUF_SIZE 500
  10.  
  11. struct addrinfo host_info;
  12. struct addrinfo *host_info_list;
  13.  
  14. int connect(const char *hostname, const char *port);
  15.  
  16. int main(int argc, char *argv[]) {
  17. if (argc != 3) {
  18. fprintf(stderr, "Usage: ./getbanner <hostname> <port>\n");
  19. exit(EXIT_FAILURE);
  20. }
  21.  
  22. int socket_fd;
  23.  
  24. char buf[BUF_SIZE];
  25.  
  26. const char *hostname = argv[1];
  27. const char *port = argv[2];
  28.  
  29. socket_fd = connect(hostname, port);
  30.  
  31. const char *message = "QUIT\n";
  32. send(socket_fd, message, strlen(message), 0);
  33.  
  34. read(socket_fd, buf, BUF_SIZE);
  35. fprintf(stdout, "%s", buf);
  36.  
  37. memset(buf, 0, BUF_SIZE);
  38. read(socket_fd, buf, BUF_SIZE);
  39. fprintf(stdout, "%s", buf);
  40.  
  41. freeaddrinfo(host_info_list);
  42. close(socket_fd);
  43. }
  44.  
  45. int connect(const char *hostname, const char *port) {
  46. int socket_fd;
  47. int status;
  48.  
  49. memset(&host_info, 0, sizeof(host_info));
  50. host_info.ai_family = AF_UNSPEC;
  51. host_info.ai_socktype = SOCK_STREAM;
  52.  
  53. status = getaddrinfo(hostname, port, &host_info, &host_info_list);
  54. if (status != 0) {
  55. fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
  56. exit(EXIT_FAILURE);
  57. }
  58.  
  59. socket_fd = socket(host_info_list->ai_family, host_info_list->ai_socktype,
  60. host_info_list->ai_protocol);
  61. if (socket_fd == -1) {
  62. fprintf(stderr, "Error: cannot create socket\n");
  63. exit(EXIT_FAILURE);
  64. }
  65.  
  66. status =
  67. connect(socket_fd, host_info_list->ai_addr, host_info_list->ai_addrlen);
  68. if (status == -1) {
  69. fprintf(stderr, "Error: cannot connect to socket\n");
  70. exit(EXIT_FAILURE);
  71. }
  72.  
  73. return socket_fd;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement