简体   繁体   English

Android功能返回IP地址

[英]Android function to return IP address

I'm sending data from android device to localhost database. 我正在将数据从android设备发送到localhost数据库。 To do this I need to use my ip address. 为此,我需要使用我的IP地址。 I can find my ip address by searching 'ipconfig' on the command prompt. 我可以通过在命令提示符下搜索“ ipconfig”来找到我的IP地址。 I just noticed that my ip address changed slightly even though im using the same wifi connection. 我只是注意到即使我使用相同的wifi连接,我的IP地址也略有变化。 The last digit of my ip address changed. 我的IP地址的最后一位数字已更改。 This needed a minor change in my code but I was wonder if there was an android function that returned your computers ip address for you so that the code could look like below. 这需要对我的代码进行较小的更改,但是我想知道是否有一个android函数为您返回了计算机的ip地址,因此代码如下所示。 Such a function would also help when using other forms of internet connection that would change your ip address. 当使用其他形式的互联网连接会更改您的IP地址时,此功能也将有所帮助。

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

first get your network-interfaces via: 首先通过以下方式获取您的网络接口:

NetworkInterface.getNetworkInterfaces();

then get the IP(s) va: 然后获取IP值va:

getInetAddresses()

Here is a function i made to get my Android Device IP. 这是我获取我的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;
}

This function receives a Boolean parameter, if True, it will return the Local Loopback IP (IE: 127.0.0.1), if False, it will return the normal IP (IE: 192.168.0.5) 此函数接收一个布尔参数,如果为True,它将返回本地回送IP(IE:127.0.0.1),如果为False,它将返回普通IP(IE:192.168.0.5)

您可以尝试连接多个IP,如果已证明返回数据是计算机IP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM