Get my wifi ip address Android

后端 未结 9 1465
無奈伤痛
無奈伤痛 2020-11-27 02:41

How can I get the ip address of my phone when it is connected under wifi?

I found a method here but it returns something like 24.182.239.255 even if I\'m under wifi

相关标签:
9条回答
  • 2020-11-27 03:23

    Add Following Permission.

     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    

    WifiManager initialize in onCreate.

     WifiManager wifiMgr = (WifiManager) getContext().getSystemService(context.WIFI_SERVICE);
    

    Use following function.

     public void WI-FI_IP() {
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
        int ip = wifiInfo.getIpAddress();
        String ipAddress = Formatter.formatIpAddress(ip);
        }
    
    0 讨论(0)
  • 2020-11-27 03:26

    Found this nice answer, https://gist.github.com/stickupkid/1250733

    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    int ipAddress = wifiInfo.getIpAddress();
    String ipString = String.format(“%d.%d.%d.%d”, (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff), (ip >> 24 & 0xff));
    
    0 讨论(0)
  • 2020-11-27 03:26

    The following code is from AOSP Settings. It get the active link's ip, not matter wifi or mobile. It's the most common way.

    http://androidxref.com/8.0.0_r4/xref/packages/apps/Settings/src/com/android/settings/deviceinfo/Status.java#251

    /**  
     * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
     * addresses.
     * @param context the application context
     * @return the formatted and newline-separated IP addresses, or null if none.
     */
    public static String getDefaultIpAddresses(ConnectivityManager cm) {                                                                      
        LinkProperties prop = cm.getActiveLinkProperties();
        return formatIpAddresses(prop);
    }    
    
    private static String formatIpAddresses(LinkProperties prop) {
        if (prop == null) return null;
        Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
        // If there are no entries, return null
        if (!iter.hasNext()) return null;
        // Concatenate all available addresses, comma separated
        String addresses = "";
        while (iter.hasNext()) {
            addresses += iter.next().getHostAddress();
            if (iter.hasNext()) addresses += "\n";
        }
        return addresses;
    }
    
    0 讨论(0)
  • 2020-11-27 03:27

    So something to consider is that Formatter.formatIpAddress(int) is being deprecated:

    This method was deprecated in API level 12. Use getHostAddress(), which supports both IPv4 and IPv6 addresses. This method does not support IPv6 addresses.

    So using formatIpAddress(int) is likely not a good long term solution, although it will work.

    Here is a potential solution if you are looking to absolutely on get the IP address for the WiFi interface:

    protected String wifiIpAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
        int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
    
        // Convert little-endian to big-endianif needed
        if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
            ipAddress = Integer.reverseBytes(ipAddress);
        }
    
        byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();
    
        String ipAddressString;
        try {
            ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
        } catch (UnknownHostException ex) {
            Log.e("WIFIIP", "Unable to get host address.");
            ipAddressString = null;
        }
    
        return ipAddressString;
    }
    

    As stated in previous responses, you need to set the following in your AndroidManifest.xml:

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    

    Note that this is only an example solution. You should take time to check for null values and so on to make sure that the UX is smooth.

    The irony is that on one hand Google is deprecating formatIpAddress(int), but still has getIpAddress() still returns an integer value. The IP address being an int also rules it out for being IPv6 compliant.

    Next is the fact that endianness may or may not be an issue. I have only tested three devices and they have all been little-endian. It seems like endianness can vary depending on the hardware, even though we are running in VMs this can still be an issue. So to be on the safe side I added an endian check in the code.

    getByAddress(byte[]) appears to want the integer value to be big endian. From researching this it appears that network byte order is big-endian. Makes sense since an address like 192.168.12.22 is a big-endian number.


    Check out HammerNet GitHub project. It implements the code above along with a bunch of sanity checks, ability to handle defaults for AVDs, unit tests, and other things. I had to implement this for an app of mine and decided to open source the library.

    0 讨论(0)
  • 2020-11-27 03:28

    If adb is installed in the terminal then do:

    Runtime.getRuntime.exec("adb", "shell", "getprop", "dhcp.wlan0.ipaddress");
    
    0 讨论(0)
  • 2020-11-27 03:32

    Formatter.formatIpAddress(int) is deprecated:

    WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
    String ipAddress = BigInteger.valueOf(wm.getDhcpInfo().netmask).toString();
    
    0 讨论(0)
提交回复
热议问题