Search code examples
c++socketsgetaddrinfoendianness

Calling socket::connect, socket::bind, socket::listen without using getaddrinfo( ) function before it


In all the example including Beej's Guide, the IP address is provided in dot notation and then it's fed to ::getaddrinfo(). This post doesn't answer my question.

After which the addrinfo struct is used for socket related functions (e.g. connect(), bind(), listen()). For example:

struct addrinfo hints, *res;
// ... create socket etc.
connect(sockfd, res->ai_addr, res->ai_addrlen);

Example
The variable ai_addr is of type sockaddr which can be safely typecasted to sockaddr_storage, sockaddr_in and sockaddr_in6.

Question:

If I typecast sockaddr to sockaddr_in (or sockaddr_in6)

sockaddr_in& ipv4 = (sockaddr_in&)(sockaddr_variable);

and feed below info:

  • ipv4.sin_family = AF_INET
  • ipv4.sin_addr = [IP Address in net byte order]
  • ipv4.sin_port = [Port number in net byte order]

Can I call the connect() method directly using above info?

connect(sockfd, &ipv4, sizeof(ipv4));

With my program it doesn't appear to work. Am I missing something, or is there a better way?

The motivation behind is that, if we have the information of IPAddress, Port etc. in socket readable format then why to go through the cycle of getaddrinfo()


Solution

  • Be sure you're placing your values in network order, here's a small example:

    #include<stdio.h>
    #include<sys/socket.h>
    #include<arpa/inet.h>
    
    int main(int argc, char *argv[])
    {
        int sock;
        struct sockaddr_in server;
    
        sock = socket(AF_INET, SOCK_STREAM, 0);
        if (sock == -1)
        {
            printf("Could not create socket\n");
        }
        printf("Socket created\n");
    
        server.sin_family = AF_INET;
        // 173.194.32.207 is a google address
        server.sin_addr.s_addr = 173 | 194 << 8 | 32 << 16 | 207 << 24;
        server.sin_port = 0x5000; // port 80
    
        if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
        {
            perror("connect failed. Error");
            return 1;
        }
    
        printf("Connected\n");
    
        close(sock);
        return 0;
    }