Untitled

 avatar
unknown
plain_text
a year ago
1.4 kB
17
Indexable

#include <stdio.h>      // for printf, fprintf
#include <stdlib.h>     // for exit
#include <string.h>     // for memset
#include <sys/types.h>  // basic system data types
#include <sys/socket.h> // socket(), AF_INET, SOCK_STREAM, etc.
#include <netdb.h>      // struct addrinfo, getaddrinfo(), gai_strerror()
int main(int argc, char *argv[]) {
    int status;
    int sockfd;
    struct addrinfo hints;
    struct addrinfo *res;

    if (argc != 2) {
        fprintf(stderr, "usage: %s port\n", argv[0]);
        exit(1);
    }
    char *port = argv[1];

    memset(&hints, 0, sizeof hints); // make sure the struct is empty
    hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever
    hints.ai_socktype = SOCK_STREAM; // TCP
    hints.ai_flags = AI_PASSIVE; // fill in my IP for me

    if ((status = getaddrinfo(NULL, port, &hints, &res)) != 0) {
        fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
        exit(1);
    }

    // int socket (int domain, int type, int protocol);
    sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    
    // int bind (int sockfd, struct sockaddr *addr, socklen_t addrlen);
    // don't need to bind bc the kernel will do it for us
    // bind(sockfd, res->ai_addr, res->ai_addrlen);

    // int connect (int sockfd, const struct sockaddr *addr, socklen_t addrlen);
    connect(sockfd, res->ai_addr, res->ai_addrlen);

    freeaddrinfo(res);
    return 0;
}
Editor is loading...
Leave a Comment