Android - 使用wifi,热点,USB或蓝牙共享时获取本地IP地址

时间:2015-10-18 15:21:27

标签: java android

当热点打开或连接到wifi网络或通过蓝牙时,我需要我的Android手机的本地IP地址。  我已经使用了这两个代码

第一个代码给出" 10.0.2.5"在所有情况下和第二个在连接到wifi网络时给出正确的IP地址。但是当热点开启时,它会给出" 0.0.0.0"
FIRST代码段

public static String getIpAddress() {
            try {
                for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                    NetworkInterface intf = (NetworkInterface) en.nextElement();
                    for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                        InetAddress 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("MASOOM", ex.toString());
            }
            return null;
        }

第二个代码段

public String getIpAddress(){
    WifiManager wifiManager = (WifiManager) this.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));
}

请提供正确的代码

1 个答案:

答案 0 :(得分:0)

String ip = "";
        try {
            Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (enumNetworkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
                Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();
                while (enumInetAddress.hasMoreElements()) {
                    InetAddress inetAddress = enumInetAddress.nextElement();
                    if (inetAddress.isSiteLocalAddress()) {
                        ip += inetAddress.getHostAddress() + " | ";
                    }
                }
            }
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ip;