天天看点

获取本机真实ip地址,去除127.0.0.1等无用地址

获取本机真实ip地址,去除127.0.0.1等无用地址

    • 完全代码
      • 附录:这也是从人家那学习而来,因为先前获取本机地址的时候有时候获取的是真实地址,有时候是127.0.0.1,这些代码是为了过滤那些不需要的地址,在此做个记录,各位想要用随便用

完全代码

package com.waving.test;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IPMain {
    public static void main(String[] args) {
        String hostIp = getHostIp();
        System.out.println("hostIp = " + hostIp);
    }


    private static String getHostIp() {
        try {
            Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ip = (InetAddress) addresses.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            && !ip.isLoopbackAddress() //loopback地址即本机地址,IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
                            && ip.getHostAddress().indexOf(":") == -1) {
                        System.out.println("本机的IP = " + ip.getHostAddress());
                        return ip.getHostAddress();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

           

附录:这也是从人家那学习而来,因为先前获取本机地址的时候有时候获取的是真实地址,有时候是127.0.0.1,这些代码是为了过滤那些不需要的地址,在此做个记录,各位想要用随便用