天天看點

擷取本機真實ip位址,去除127.0.0.1等無用位址

擷取本機真實ip位址,去除127.0.0.1等無用位址

    • 完全代碼
      • 附錄:這也是從人家那學習而來,因為先前擷取本機位址的時候有時候擷取的是真實位址,有時候是127.0.0.1,這些代碼是為了過濾那些不需要的位址,在此做個記錄,各位想要用随便用

完全代碼

package com.waving.test;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IPMain {
    public static void main(String[] args) {
        String hostIp = getHostIp();
        System.out.println("hostIp = " + hostIp);
    }


    private static String getHostIp() {
        try {
            Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ip = (InetAddress) addresses.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            && !ip.isLoopbackAddress() //loopback位址即本機位址,IPv4的loopback範圍是127.0.0.0 ~ 127.255.255.255
                            && ip.getHostAddress().indexOf(":") == -1) {
                        System.out.println("本機的IP = " + ip.getHostAddress());
                        return ip.getHostAddress();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

           

附錄:這也是從人家那學習而來,因為先前擷取本機位址的時候有時候擷取的是真實位址,有時候是127.0.0.1,這些代碼是為了過濾那些不需要的位址,在此做個記錄,各位想要用随便用