java 获取我的 LAN ip 地址 (192.168.xxxx) (IPV4)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17252018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:27:16  来源:igfitidea点击:

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

javaandroidinetaddress

提问by Vishnudev K

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

在我的 android 设备中,我试图找到它的 IP 地址(IPV4)。
如果我执行以下代码

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.

代码给了我 127.0.0.1。
我想获得实际 IP 198.168.xx.xx。

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

(在我的电脑中,同样的代码给了我实际的 IP。)

回答by Ayush

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.

也添加在 mainfest.

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

回答by Ken Wolf

You can use this to get your IP address.

您可以使用它来获取您的 IP 地址。

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"

这将它作为“XXXX”形式的字符串返回

The only permission you need in your manifest.xmlis

您需要的唯一许可manifest.xml

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