开发者

Android How to find Dynamic IP from device? [duplicate]

开发者 https://www.devze.com 2023-01-09 09:20 出处:网络
This question already has answers here: How to get IP address of the device from code? (31 answers) Closed 7 years ago.
This question already has answers here: How to get IP address of the device from code? (31 answers) Closed 7 years ago.

I have method to find the DHCP address and host address. how to find the dynamic ip address assigned to my device. I am able get the address from http://www.ip2开发者_如何学JAVAlocation.com/default.aspx

how to get this IP in device?


ipString = String.format( 
    "%d.%d.%d.%d", 
    (ip & 0xff), 
    (ip >> 8 & 0xff),
    (ip >> 16 & 0xff),
    (ip >> 24 & 0xff));


You could use an external server to request your IP, like @Midday suggests. This is probably the easiest solution. The problem is that you will have to depend on the network and the remote server which might not always be reliable.

You can also get it directly from your device, but you have to jump through hoops to do so – getting your device's IP address isn't as simple as it should be on Android.

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();

Notice that the ipAddress is an integer.

For instance if your IP address is "86.52.119.245":

  • the int returned by getIpAddress will be 4118230102.
  • Translated into binary this number is: 11110101 01110111 00110100 01010110.
  • Convert each byte into a decimal, and then you get the numbers: 80 35 83 10
  • Notice that the numbers are in network order so you have to flip it.

Hope it helps.


if you want the external IP this website can help you, they also have an XML API hope this helps. If you need the local IP (if on WIFI) there should be something in the Android api


This helped me get my IPv4 IP. I got it from another post but some search results show this one.

public static String getMyIp(){
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    if(InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        }
    } catch (SocketException ex) {
        Log.e("NetworkSettings", "There was a socket error: " + ex.toString());
    }
    return null;
}

Taken from "How to get my ip address?" post and added check for IPv4 (it returned IPv6 for me)

0

精彩评论

暂无评论...
验证码 换一张
取 消