如何以编程方式获取Android手机的IP地址....?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26402218/
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-08-20 11:21:51  来源:igfitidea点击:

How to get the ip address of an android mobile programatically ....?

android

提问by krishnan

I want exact IP address of android device when it will connected to a network through wifi! can any one help me how to get the ip address while the mobile is connected to a network and how to get the address through pro-grammatically ..enter image description here

当它通过wifi连接到网络时,我想要android设备的确切IP地址!任何人都可以帮助我如何在移动设备连接到网络时获取 ip 地址以及如何以编程方式获取地址..在此处输入图片说明

回答by Mohamed ALOUANE

I used this and it workd !

我用了这个,它奏效了!

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

Below permissions in the manifest file.

下面是清单文件中的权限。

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

回答by rana_sadam

You can use this method to get IP address of the device pass true for IPv4 and false for IPv6

您可以使用此方法获取设备的 IP 地址,IPv4 为 true,IPv6 为 false

 public static String getIPAddress(boolean useIPv4) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress();
                    //boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    boolean isIPv4 = sAddr.indexOf(':')<0;

                    if (useIPv4) {
                        if (isIPv4) 
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
                            return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
                        }
                    }
                }
            }
        }
    } catch (Exception ex) { } // for now eat exceptions
    return "";
}

Thanks to this ans How to get IP address of the device?

感谢这个 ans如何获取设备的 IP 地址?