码迷,mamicode.com
首页 > 其他好文 > 详细

获取主机ip地址

时间:2017-04-12 18:41:13      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:property   sock   port   name   catch   doc   sys   docker   date   

  Linux或windows的ip地址

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * 
 * @author LiCJ
 *    @date 2017.04.12
 */
public class WebTools {
    /**
     * 获取本地IP地址
     * @return
     * @throws UnknownHostException
     * @throws SocketException
     */
     public static String getLocalIP() throws UnknownHostException, SocketException {
            if (isWindowsOS()) {
                return InetAddress.getLocalHost().getHostAddress();
            } else {
                return getLinuxLocalIp();
            }
        }
     /**
      * 获取本地Host名称
      * @return
      * @throws UnknownHostException
      */
        public static String getLocalHostName() throws UnknownHostException {
            return InetAddress.getLocalHost().getHostName();
        }
     /**
      *  获取Linux下的IP地址
      * @return
      */
    private static String getLinuxLocalIp() {
         String ip = "";
            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    String name = intf.getName();
                    if (!name.contains("docker") && !name.contains("lo")) {
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress()) {
                                String ipaddress = inetAddress.getHostAddress().toString();
                                if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                                    ip = ipaddress;
                                }
                            }
                        }
                    }
                }
            } catch (SocketException ex) {
                ex.printStackTrace();
            }
            return ip;
    }
/**
 * 判断操作系统是否是Windows
 * @return
 */
    private static boolean isWindowsOS() {
        boolean isWindowsOS = false;
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().indexOf("windows") > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }
}

 

获取主机ip地址

标签:property   sock   port   name   catch   doc   sys   docker   date   

原文地址:http://www.cnblogs.com/woftlcj/p/6700515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!