shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.walker.infrastructure.utils;
 
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
 
public class NetworkUtils {
 
    /**
     * 获取本机正在使用的网卡IP地址。
     * @return
     * @date 2023-09-05
     */
    public static final String getLocalHostIp(){
        Enumeration<NetworkInterface> interfaces = null;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            System.out.println("获取本机网卡信息错误:" + e.getMessage());
            return StringUtils.EMPTY_STRING;
//            throw new ApplicationRuntimeException("获取本机网卡信息错误:" + e.getMessage(), e);
        }
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                if (!address.isLoopbackAddress() && !address.isLinkLocalAddress() && address.isSiteLocalAddress()) {
                    return address.getHostAddress();
                }
            }
        }
        return StringUtils.EMPTY_STRING;
    }
}