Android get IP-Address of a hotspot providing device

前端 未结 6 1377
半阙折子戏
半阙折子戏 2020-12-05 05:27

I\'m currently using

public static String getLocalIPAddress(WifiManager wm){
    return Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
}
         


        
6条回答
  •  没有蜡笔的小新
    2020-12-05 05:51

    Though this is an old question, but this might help someone. This will return the ip address of your device, as long as you've turned on the hotspot.

    private String getIpAddress() {
        String ip = "";
        try {
            Enumeration enumNetworkInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (enumNetworkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = enumNetworkInterfaces
                        .nextElement();
                Enumeration enumInetAddress = networkInterface
                        .getInetAddresses();
                while (enumInetAddress.hasMoreElements()) {
                    InetAddress inetAddress = enumInetAddress.nextElement();
    
                    if (inetAddress.isSiteLocalAddress()) {
                        ip += "SiteLocalAddress: "
                                + inetAddress.getHostAddress() + "\n";
                    }
                }
            }
    
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            ip += "Something Wrong! " + e.toString() + "\n";
        }
        return ip;
    }
    

提交回复
热议问题