Home > Java > javaTutorial > body text

Java method to obtain local IP

大家讲道理
Release: 2016-11-10 10:29:46
Original
2013 people have browsed it

获取本地服务器IP经常会出现127.0.0.1,0:0:0:0:0:0:0:1,fe80:0:0:0:960:74bd:e1a0:e5b9%11 这些情况,以下代码可解决此问题

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());
        }
    }
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!