java獲取本機的ip地址

qking93415981發表於2020-04-06
 

可以用如下程式碼:

           InetAddress inet = InetAddress.getLocalHost();
            System.out.println("本機的ip=" + inet.getHostAddress());

在window下面可以工作。在linux下返回127.0.0.1。主要是在linux下返回的是/etc/hosts中配置的localhost的ip地址,而不是網路卡的繫結地址。後來改用網路卡的繫結地址,可以取到本機的ip地址:) 

        Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip 
= null;
        
while (netInterfaces.hasMoreElements()) {
            NetworkInterface ni 
= (NetworkInterface) netInterfaces.nextElement();
            System.out.println(
"---------------"+ni.getName()+"---------------");
            
            Enumeration
<InetAddress> inets = ni.getInetAddresses();//這個疊代不能少,否則在Linux下會有錯
            
while(inets.hasMoreElements()){
                ip 
= inets.nextElement();
                System.out.println(ip.getHostName() 
+ "=" + ip.getHostAddress());
                
                
if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":"== -1) {
                    LOCAL_IP 
= ip.getHostAddress();
                    System.out.println(LOCAL_IP 
+ " is site local address!");
                    
//break;
                } else {
                    ip 
= null;
                }
            }
        }
        System.out.println(
"**********--->LOCAL_IP =" + LOCAL_IP);

相關文章