`
thrillerzw
  • 浏览: 138722 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

获取ip、主机名

    博客分类:
  • java
 
阅读更多
protected  String getIp() {
         Enumeration<NetworkInterface> netInterfaces = null;
         try {
             netInterfaces = NetworkInterface.getNetworkInterfaces();
             while (netInterfaces.hasMoreElements()) {
                 NetworkInterface ni = netInterfaces.nextElement();
                 Enumeration<InetAddress> ips = ni.getInetAddresses();
                 while (ips.hasMoreElements()) {
                     InetAddress ip = ips.nextElement();
                     if (ip.isSiteLocalAddress()) {
                         return ip.getHostAddress();
                     }
                 }
             }
         } catch (Exception e) {
          e.printStackTrace();
         }
         return "";
     }

  

 public static final String ip = null;
	public static final hostName = null;
 	static {
		
		try {
			hostName = InetAddress.getLocalHost().getHostName();
			InetAddress ipAddr[] = InetAddress.getAllByName(hostName);
			for (int i = 0; i < ipAddr.length; i++) {
				ip = ipAddr[i].getHostAddress();
				if (ip.startsWith(LOCAL_IP_STAR_STR)) {
					break;
				}
			}
			if (ip == null) {
				ip = ipAddr[0].getHostAddress();
			}

		} catch (UnknownHostException e) {
			
		}
		
	}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics