Search code examples
c++socketsdns

C++ socket connect not working when not using IP


I am trying to connect to my Java server with my C++ client through a dns.

So when I type the dns name instead of my localip, It won't connect. The following code doesn't work:

sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("blalblalb.no-ip.com");
addr.sin_port = htons(4444);

But when I type the ip-address of the dns, it works:

sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("174.554.xx.xxx");
addr.sin_port = htons(4444);

Solution

  • inet_addr() is supposed to take an address in numbers-and-dots notation only.

    If you want to use a hostname, use getaddrinfo() instead. The link to the manual page has a linux example (and here a Windows example).

    Please note that inet_addr() only handles IPv4 adresses and is not compatible with IPv6 format. You could consider inet_ptron() for a more future proof development.