用java獲取本地ip

 

通常,我們都是用以下代碼來獲取本地ip地址的

InetAddress.getLocalHost().getHostAddress()  


這種方法在linux卻只能取到127.0.0.1這個讓人無奈的地址。。。這簡直是讓人不能忍受的啊。。。這種地址不用獲取,我們誰不知道。。。
在網上搜索了很多,發現說這個問題的並不多,所以,我把找到的一段代碼分享給大家。。。當然這段代碼需要jdk1.5以上版本

Enumeration<NetworkInterface> netInterfaces = null;   
	try {   
	    netInterfaces = NetworkInterface.getNetworkInterfaces();   
	    while (netInterfaces.hasMoreElements()) {   
	        NetworkInterface ni = netInterfaces.nextElement();   
	        System.out.println("DisplayName:" + ni.getDisplayName());   
	        System.out.println("Name:" + ni.getName());   
	        Enumeration<InetAddress> ips = ni.getInetAddresses();   
	        while (ips.hasMoreElements()) {   
	            System.out.println("IP:"  
	            + ips.nextElement().getHostAddress());   
	        }   
	    }   
	} catch (Exception e) {   
	    e.printStackTrace();   
	}  


這段代碼會輸出計算機中所有設備的ip,找需要的用吧,呵呵

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章