Home  >  Q&A  >  body text

使用Java怎么样获取本地IP?

获取本地服务器IP经常会出现127.0.0.1,0:0:0:0:0:0:0:1,fe80:0:0:0:960:74bd:e1a0:e5b9%11 这些情况,怎么解决?

大神,求带!大神,求带!2845 days ago1082

reply all(2)I'll reply

  • 数据分析师

    数据分析师2017-09-30 23:58:23

    How to get local IP using Java? -PHP Chinese website Q&A-How to obtain local IP using Java? -PHP Chinese website Q&A

    Let’s take a look and learn.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-01-24 15:38:52

    以下代码可解决此问题:

    public static void main(String[] args) {
            try {
                Enumeration<networkinterface> enumeration = NetworkInterface
                        .getNetworkInterfaces();
                while (enumeration.hasMoreElements()) {
                    NetworkInterface networkInterface = enumeration.nextElement();
                    if (networkInterface.isUp()) {
                        Enumeration<inetaddress> addressEnumeration = networkInterface
                                .getInetAddresses();
                        while (addressEnumeration.hasMoreElements()) {
                            String ip = addressEnumeration.nextElement()
                                    .getHostAddress();
                            final String REGX_IP = "((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";
                            if (ip.matches(REGX_IP) && !ip.equals("127.0.0.1")) {
                                System.out.println(ip);
                            }
       
                        }
                    }
                }
            } catch (Exception e) {
                log.error("获取本机ip出现异常,异常信息为:" + e.getMessage());
            }
        }</inetaddress></networkinterface>


    reply
    0
  • Cancelreply