Android功能返回IP地址

时间:2015-03-24 18:30:53

标签: java android

我将数据从Android设备发送到localhost数据库。要做到这一点,我需要使用我的IP地址。我可以通过搜索' ipconfig'找到我的IP地址。在命令提示符下。我刚注意到即使我使用相同的wifi连接,我的IP地址也略有改变。我的IP地址的最后一位改变了。这需要对我的代码进行微小的更改,但我很想知道是否有一个android函数为您返回了您的计算机IP地址,以便代码看起来如下所示。当使用其他形式的互联网连接改变你的IP地址时,这样的功能也会有所帮助。

HttpPost httpPost = new HttpPost("http://" + ipAddressFunction() + "/linker.php");// home wifi 

3 个答案:

答案 0 :(得分:0)

首先通过以下方式获取您的网络接口:

NetworkInterface.getNetworkInterfaces();

然后获得IP(s)va:

getInetAddresses()

答案 1 :(得分:0)

这是我用来获取Android设备IP的功能。

//Get The Local IP Addresses
private String GetLocalIPAddress(Boolean LoopBack)
{
    try
    {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
        {
            NetworkInterface intf = en.nextElement ();  
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
            {
                InetAddress inetAddress = enumIpAddr.nextElement ();  
                if(inetAddress.getHostAddress().contains("."))
                {
                    if(inetAddress.isLoopbackAddress() == LoopBack)
                    {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        }
    }
    catch (Exception e)
    {
        Log.d(this.getClass().toString(), "Failed Getting Local IP\n\n" + e.getMessage());
    }
    return null;
}

此函数接收一个布尔参数,如果为True,则返回本地环回IP(I.E:127.0.0.1),如果为False,则返回正常IP(I.E:192.168.0.5)

答案 2 :(得分:-1)

如果返回数据被证明是计算机IP

,您可以尝试连接多个IP
相关问题