【问题标题】:Java get local internal AddressJava获取本地内部地址
【发布时间】:2017-10-27 11:19:56
【问题描述】:

我想要的是,当热点也与 4G LTE 连接时,如何获取热点的内部 IP 地址。我尝试过的方法返回外部 IP 地址而不是本地 IP 地址。

示例:100.70.1.23 不是 192.168.43.1

我想要本地地址“192.168.43.1”忽略外部地址

public String getDeviceIpAddress() {

    String ip = "None";

    try {
        //Loop through all the network interface devices
        for (Enumeration<NetworkInterface> enumeration = NetworkInterface
                .getNetworkInterfaces(); enumeration.hasMoreElements(); ) {
            NetworkInterface networkInterface = enumeration.nextElement();
            //Loop through all the ip addresses of the network interface devices
            for (Enumeration<InetAddress> enumerationIpAddr = networkInterface.getInetAddresses(); enumerationIpAddr.hasMoreElements(); ) {
                InetAddress inetAddress = enumerationIpAddr.nextElement();
                //Filter out loopback address and other irrelevant ip addresses
                if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == 4) {
                    //device ip address
                    ip = inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ignored) {}

    return ip;
}

【问题讨论】:

  • 你在那个for循环中获得了多少IP?如果还有更多,您只会得到最后一个。首先将它们全部记录下来。并在第一次找到时打破循环。
  • 是的,成功了!

标签: java android networking ip


【解决方案1】:

如果我没有理解错,你可以这样理解:

public String getMyFacesIp() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while(interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            if(iface.isLoopback() || !iface.isUp()) {
                continue;
            }

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while(addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                ip = addr.getHostAddress();
                if(ip.startsWith("192")) {
                    return ip;
                }
            }
        }
    } catch (Exception e) {}
    return ip;

}

【讨论】:

  • 我不推荐“192”,因为任何人都可以改变它。
猜你喜欢
  • 2013-08-19
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
  • 2012-04-12
  • 2011-02-25
  • 1970-01-01
  • 2017-04-16
  • 1970-01-01
相关资源
最近更新 更多