Getting My LAN ip address (192.168.xxxx) (IPV4)

橙三吉。 提交于 2019-12-18 12:17:45

问题


In my android device I am trying to find its IP address(IPV4).
If I do the following code

InetAddress inet = InetAddress.getLocalHost();
System.out.println(inet.getHostAddress()); //giving me 127.0.0.1

The code is giving me 127.0.0.1.
I wanted to get the actual IP 198.168.xx.xx.

(In My pc the same code giving me the actual IP though.)


回答1:


public static String getIpAddress() { 
            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()&&inetAddress instanceof Inet4Address) {
                            String ipAddress=inetAddress.getHostAddress().toString();
                            Log.e("IP address",""+ipAddress);
                            return ipAddress;
                        }
                    }
                }
            } catch (SocketException ex) {
                Log.e("Socket exception in GetIP Address of Utilities", ex.toString());
            }
            return null; 
    }

Give permissions

Also add in mainfest.

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



回答2:


You can use this to get your IP address.

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
return String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
        (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));

This returns it as a String in the form "X.X.X.X"

The only permission you need in your manifest.xml is

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


来源:https://stackoverflow.com/questions/17252018/getting-my-lan-ip-address-192-168-xxxx-ipv4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!