getsockname()在connect()到公共IP之后显示127.0.0.1

时间:2018-01-29 22:05:46

标签: sockets loopback winsock2

我正在努力理解这一点。问题出现在以下机器上:

  • 远程(我无权访问)
  • 运行Windows 7
  • 没有运行代理或VPN(或者我被告知)

我的应用程序有一段代码,试图快速确定操作系统更喜欢的接口。它执行以下操作:

// Create a socket
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);

// Resolve DNS query
DWORD dwRemoteIp = GetHostAddr("www.google.com")
// I've simplified the call here, but "www.google.com" resolves to 172.217.3.100 in host byte order, so the resolution is correct

// Create the remote address to connect to
sockaddr_in remoteaddr = {0};
remoteaddr.sin_family = AF_INET;
remoteaddr.sin_addr.s_addr = htonl(dwRemoteIp);
remoteaddr.sin_port = htons(80);

// Connect the socket
if (0 == connect(sock, (struct sockaddr*)&remoteaddr, sizeof(remoteaddr))) {

    // The connection succeeded -- see which local address was bound to
    sockaddr_in localaddr = {0};
    int len = sizeof(localaddr);
    if (0 == getsockname(sock, (struct sockaddr*)&localaddr, (socklen_t *)&len)) {

        // Here is where I see dwLocalIp == 0x7F000001, or 127.0.0.1
        DWORD dwLocalIp = ntohl(localaddr.sin_addr.s_addr);
    }
}

这可能会发生什么?

0 个答案:

没有答案