Getting IP address in a readable form android code

后端 未结 4 981
囚心锁ツ
囚心锁ツ 2021-01-26 04:31

I am new to android development and I am doing an application which sends the IP address of an android device to another one by sms. I need to get the IP in decimal like this 19

4条回答
  •  庸人自扰
    2021-01-26 04:48

    This post explains how to get the IP of the device.

    This bit of code (taken from the aforementioned post) should get you the IP address the correct way:

    public String getLocalIpAddress() {
        try {
            for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(LOG_TAG, ex.toString());
        }
        return null;
    }
    

提交回复
热议问题