获取系统IP的方法

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


   /**  
	* @ClassName: CustomSystemUtil 
	* @Description: TODO(用于获取系统相关信息)  
	* @author xushaowen
	* @date 2019年2月27日 上午11:30:57  
	*    
	*/
public class CustomSystemUtil {
    /** 内网IP */
    private static String IN_INTERNET_IP = getInInternetIp();
    /** 外网IP */
    public static String OUT_INTERNET_IP = getOutInternetIp();

    private CustomSystemUtil(){}

    /**
     * 获得内网IP
     * @return 内网IP
     */
    private static String getInInternetIp(){
        try{
            return InetAddress.getLocalHost().getHostAddress();
        } catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 获得外网IP
     * @return 外网IP
     */
    private static String getOutInternetIp(){
        try{
            Enumeration networks = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            Enumeration addrs;
            while (networks.hasMoreElements())
            {
                addrs = networks.nextElement().getInetAddresses();
                while (addrs.hasMoreElements())
                {
                    ip = addrs.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            && ip.isSiteLocalAddress()
                            && !ip.getHostAddress().equals(INTRANET_IP))
                    {
                        return ip.getHostAddress();
                    }
                }
            }

            // 如果没有外网IP,就返回内网IP
            return IN_INTERNET_IP;
        } catch(Exception e){
            throw new RuntimeException(e);
        }
    }
}

你可能感兴趣的:(笔记,获取IP方法)