简体   繁体   中英

How to get Internet IP from struct sockaddr (not router IP)?

I have a server coded in C. After the accept() , I want to get the IP address from the sockaddr. But the IP address I get is the one from the VM I'm on : 10.0.xx, not the internet IP. The VM is hosted on a computer that has a real IP, which is the one I would like to get.

The port forwarding has been done. Example : I have 2 computers running the same VM, so they have the same VM local IP (10.0.xx). The first VM launches the server, the second uses telnet to connect using the real server's IP (147.xxx). The connection is established correctly, but the IP I get in the sockaddr is the VM one.

Do you know how to resolve it?

You'll need a "third party" outside, eg a (web) server that will just return/print the remote IP of the active connection. That way you're able to get your "internet ip" when behind a local NAT.

uint32_t getip(int clientSock)
{
    socklen_t len;
    struct sockaddr_storage addr;
    struct sockaddr_in *s;

    len = sizeof addr;
    int res = getpeername(clientSock, (struct sockaddr*)&addr, &len);
    if ( 0 != res ) {
            return 0;
    }

    if (addr.ss_family == AF_INET)
            s = (struct sockaddr_in *)&addr;
    else // apparently AF_INET6
        return 0;

    return s->sin_addr.s_addr;
}

Maybe I'm wrong with this... however it seems that your VM has set up an "internal" network for itself (hence the 10.0.... IPs). In my experience this happened when the VM was configured to have NAT type of networking and the DHCP VM service was running. Try with Bridged. This might give you more than one network interface, so you will have to tell the server specifically to which interface it should bind/listen to. There is some code for getting the interfaces for various operating systems at http://pici-nms.cvs.sourceforge.net/viewvc/pici-nms/common/NetworkInterface.cpp?view=markup and also for specifically binding it to a requested interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM