zhs
2025-04-16 3c46b264b86bb38984370f685c6866c5f7784808
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.ruoyi.common.utils;
 
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
 
public class IPUtils {
 
    public static String getIp() {
        try {
            // 获取所有网络接口
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
 
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                // 获取每个网络接口的所有IP地址
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    // 打印IP地址
                    System.out.println("IP address: " + inetAddress.getHostAddress());
                    return inetAddress.getHostAddress();
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
 
        }
        return null;
    }
 
    public static String getIp2() {
        try {
            // 获取本地主机
            InetAddress localhost = InetAddress.getLocalHost();
            System.out.println("本机名称: " + localhost.getHostName());
            System.out.println("本机 IP 地址: " + localhost.getHostAddress());
 
            // 获取所有与本地主机关联的 IP 地址
            InetAddress[] allLocalAddresses = InetAddress.getAllByName(localhost.getHostName());
            for (InetAddress address : allLocalAddresses) {
                System.out.println("本机所有 IP 地址: " + address.getHostAddress());
                return address.getHostAddress();
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }
}