JAVA获取IP地址

时间:2013-11-20 17:59:11

标签: java android ip inet

我正在开发一个Android应用程序,需要知道设备IP。

我尝试使用Inet4Address.getLocalHost().getHostAddress(),但它提供127.0.0.1

所以我正在与发送ip的服务器建立HTTP连接。

但是当设备和请求的服务器之间存在网关时,此过程会产生问题。在这种情况下,我没有获得网络的设备IP而是获得网关ip。

请帮忙。

感谢。

1 个答案:

答案 0 :(得分:2)

首先,您可能有几个网络接口,其中一个是lo。 其次,你可能已经设置了ipv4和ipv6,即每个网络接口有几个ip地址。 因此,您需要定义要使用的ipaddress和net接口,然后进行过滤。如果您只是获取第一个地址,您将得到与Inet4Address.getLocalHost().getHostAddress()

之后相同的结果

假设你想获得你找到的第一个非环回接口的ipv4(ipv6)地址。然后,以下代码给出了ip:

static InetAddress ip() throws SocketException {
    Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
    NetworkInterface ni;
    while (nis.hasMoreElements()) {
        ni = nis.nextElement();
        if (!ni.isLoopback()/*not loopback*/ && ni.isUp()/*it works now*/) {
            for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
                //filter for ipv4/ipv6
                if (ia.getAddress().getAddress().length == 4) {
                    //4 for ipv4, 16 for ipv6
                    return ia.getAddress();
                }
            }
        }
    }
    return null;
}

public static void main(String[] args) throws SocketException {
    System.out.println(ip());
}