3

The code I used show below:

ANSICHAR HostName[256];
gethostname(HostName,256);

struct addrinfo *AddrInfo = NULL;
getaddrinfo(HostName, NULL, NULL, &AddrInfo);

for (struct addrinfo *i = AddrInfo; i != NULL; i = i->ai_next)
{
    if (i->ai_family == AF_INET)
    {
        const in_addr &IP = ((sockaddr_in *) i->ai_addr)->sin_addr;
        if (IP.s_addr != 0)
        {
            Addr.SetIp(IP);
            break;
        }
    }
}

The problem is "HostName" got by "gethostname(HostName,256)" is "localhost". So the final IP I get is "127.0.0.1". It diffent between the IP address I get used "adb shell ifconfig wlan0".

How can I get the correct IP address?

jonny
  • 3,022
  • 1
  • 17
  • 30
thistl
  • 31
  • 1
  • 2
  • This is a duplicate question. Android NDK allows you to use the same methods as on Linux: http://stackoverflow.com/questions/212528/linux-c-get-the-ip-address-of-local-computer – BitBank Feb 08 '12 at 18:02
  • 3
    @BitBank Are you sure this is a duplicate? I just tried to compile using `getifaddrs()` with the Android NDK r8d and I get the error `undefined reference to 'getifaddrs'`. Perhaps it is not implemented in Android. – BigMacAttack Jan 27 '13 at 20:54
  • 1
    You may be right. For my app, I get the local IP address in Java: WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); – BitBank Jan 27 '13 at 21:53
  • Indeed, getifaddrs is not available until API 24, IIRC. Most devices cannot use that function. – Jon McClung Jul 11 '18 at 18:39

0 Answers0