首页 > 其他 > 详细

获取本地IP方法

时间:2015-11-09 21:04:05      阅读:214      评论:0      收藏:0      [点我收藏+]

获取本地服务器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());
		}
	}



获取本地IP方法

原文:http://my.oschina.net/guoenzhou/blog/528204

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!