Jason Jason - 1 year ago 78
C Question

Can I use inet_pton to set a textual address for my TCP socket server like "device1.local"?

I've written a TCP socket in C and it needs to work with a mobile app that connects to this address over a local network: "


Every example I find for using
to set the server address has either an IPV4 address that looks like this:
, or an IPV6 address that looks like this:
. Which format do I specify if I want my client to telnet to "
" instead of a numeric or hex address? How do I set up my TCP socket server to answer that address?

This doesn't work:

local_socket = socket(AF_INET6, SOCK_STREAM, 0);
if(local_socket < 0) {
printf("unable to create socket\n");
return false;
printf("socket created\n");

bzero((void *)&server_address, sizeof(server_address));
server_address.sin6_family = AF_INET6;
int s_code = inet_pton(AF_INET6, "device1.local", &server_address.sin6_addr);
server_address.sin6_port = htons(port_number);

printf("inet_pton returned: %d\n", s_code);

inet_ntop(AF_INET6, &server_address.sin6_addr, str, INET6_ADDRSTRLEN);
printf("address from inet_ntop(): %s\n", str);

Here's the output:

socket created
inet_pton returned: 0
address from inet_ntop(): ::

I realize I'm probably demonstrating a fundamental lack of understanding about how the internet (or local networks) work. Any relevant links that you can give me so I can learn more about how custom textual addresses work would be appreciated.

Answer Source

The .local TLD is reserved for mDNS, as described in RFC 6762.

Therefore for device.local to work your local system should be set with device as its hostname and should be running a Bonjour service (built-in to Windows and OSX, available as Avahi on Linux).

Once that's done, your application doesn't need to do anything special at all - it should just bind to INADDR_ANY and accept incoming connections on any interface.

On the client side, the getaddrinfo() function should be able to hook into mDNS and resolve the name to the correct IP address accordingly.