InetAddress.getLocalHost().getHostAddress()獲取的是127.0.0.1,怎樣獲取真實地址

原文鏈接:https://blog.csdn.net/myfmyfmyfmyf/article/details/53126806

版權聲明:本文爲CSDN博主「牟雲飛」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/myfmyfmyfmyf/article/details/53126806

使用InetAddress.getLocalHost().getHostAddress()讀取host文件,在linux中獲取ip時將獲取127.0.0.1。

這裏通過“can use getNetworkInterfaces()+getInetAddresses() to obtain all IP addresses for this node”獲取本本地真實IP,方法:NetworkInterface.getNetworkInterfaces()
window下:
在這裏插入圖片描述
linux下:
在這裏插入圖片描述

package muyunfei.getip;
 
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
//牟雲飛  muyunfei
public class GetIpMain {
	public static void main(String[] args) {
		try {
			//使用InetAddress.getLocalHost().getHostAddress()打印
			System.out.println("InetAddress.getLocalHost().getHostAddress():"+InetAddress.getLocalHost().getHostAddress());     
			System.out.println("打印所有IP列表信息:");
			GetIpMain ip = new GetIpMain();
			System.out.println("本機地址:"+ip.getIpAdd());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 根據網卡獲得IP地址
	 * @return
	 * @throws SocketException
	 * @throws UnknownHostException
	 */
	public  String getIpAdd() throws SocketException, UnknownHostException{
		String ip="";
		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();) {
                    //獲得IP
                	InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String ipaddress = inetAddress.getHostAddress().toString();
                        if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                            
                        	System.out.println(ipaddress);
                            if(!"127.0.0.1".equals(ip)){
                            	ip = ipaddress;
                            }
                        }
                    }
                }
            }
        }
		return ip;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章