java - 获取我的局域网 IP 地址 (192.168.xxxx) (IPV4)

标签 java android inetaddress

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

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

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

(在我的电脑中,相同的代码为我提供了实际的 IP。)

最佳答案

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; 
    }

授予权限

同时在 mainfest 中添加。

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

关于java - 获取我的局域网 IP 地址 (192.168.xxxx) (IPV4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17252018/

相关文章:

java - HID 兼容游戏 Controller Java 接口(interface)

java - 如何获得文件的正确文件创建日期?

javascript - 如何创建内容 slider 的箭头(React-Native)?

Java InetAddressClass getAllByNAme 方法

java - 在 android-priority-jobqueue 中检索当前 Activity 作业列表

android - 使用 LocationManager 检查权限的服务

java - SharedPreferences 不会发送位图 : Failed to allocate memory

Java InetAddress 失败

java - 在 Java 中解析 JSON 字符串