How to determine IPv4 versus v6 clients?

This applies to any TCP server where family = AF_INET6 (so will accept both v4/v6 clients)

v4 or v6 clients can connect as expected, however family is always v6.

In particular it is a “mapped” v4 address in v6. For example:

0::FFFF:192.168.1.1

The given example code in the Digi NET+OS .chm help file will not work:


theChildFd = accept( theSocketFd, (struct sockaddr*)&theClientAddr, &theClientAddrLen );
if (theChildFd < 0)     {
         printf("Accept failed
");
         return;     
}
/* Check if the connection is IPv4 or IPv6 */
if (theClientAddr.ss_family == AF_INET)     {         
        printf("the connection is IPv4
");     
}     
if (theClientAddr.ss_family == AF_INET6)     {         
        printf("the connection is IPv6
");     
}

Any hints?

I’m pretty sure the above will work, have you tried:

    char *addr = NULL;
    char buffer[128];

    if (theClientAddr->ss_family == AF_INET6)
        addr = (char *)&server->addr.ipv6.sin6_addr;
    else if (theClientAddr->ss_family == AF_INET)
        addr = (char *)&server->addr.ipv4.sin_addr;

    if (addr != NULL)
    {
        inet_ntop(theClientAddr->ss_family, (void *)addr, buffer, 128);
        printf("%s

", buffer);
}