Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstring>
- #include <netdb.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/socket.h>
- #include <sys/types.h>
- #include <unistd.h>
- #define BUF_SIZE 500
- struct addrinfo host_info;
- struct addrinfo *host_info_list;
- int connect(const char *hostname, const char *port);
- int main(int argc, char *argv[]) {
- if (argc != 3) {
- fprintf(stderr, "Usage: ./getbanner <hostname> <port>\n");
- exit(EXIT_FAILURE);
- }
- int socket_fd;
- char buf[BUF_SIZE];
- const char *hostname = argv[1];
- const char *port = argv[2];
- socket_fd = connect(hostname, port);
- const char *message = "QUIT\n";
- send(socket_fd, message, strlen(message), 0);
- read(socket_fd, buf, BUF_SIZE);
- fprintf(stdout, "%s", buf);
- memset(buf, 0, BUF_SIZE);
- read(socket_fd, buf, BUF_SIZE);
- fprintf(stdout, "%s", buf);
- freeaddrinfo(host_info_list);
- close(socket_fd);
- }
- int connect(const char *hostname, const char *port) {
- int socket_fd;
- int status;
- memset(&host_info, 0, sizeof(host_info));
- host_info.ai_family = AF_UNSPEC;
- host_info.ai_socktype = SOCK_STREAM;
- status = getaddrinfo(hostname, port, &host_info, &host_info_list);
- if (status != 0) {
- fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
- exit(EXIT_FAILURE);
- }
- socket_fd = socket(host_info_list->ai_family, host_info_list->ai_socktype,
- host_info_list->ai_protocol);
- if (socket_fd == -1) {
- fprintf(stderr, "Error: cannot create socket\n");
- exit(EXIT_FAILURE);
- }
- status =
- connect(socket_fd, host_info_list->ai_addr, host_info_list->ai_addrlen);
- if (status == -1) {
- fprintf(stderr, "Error: cannot connect to socket\n");
- exit(EXIT_FAILURE);
- }
- return socket_fd;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement