[Java] Obtain the server IP address

background

I made an alert email before. In some business scenarios, an alert email should be sent to the developer if the program fails to execute. Because there are multiple servers in the same environment, in order to quickly troubleshoot problems, I hope to add the IP of the machine to the email header.

achieve

import lombok.extern.slf4j.Slf4j;

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

/**
 * 机器ip工具类
 *
 * @8102 2020/3/13
 */
@Slf4j
public class IPUtil {

    /**
     * 获取linux服务器ip
     * @return
     */
    public static String getLinuxLocalIp() {
        String ip = "";
        try {
            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(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress = inetAddress.getHostAddress().toString();
                            if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                                ip = ipaddress;
                            }
                        }
                    }
                }
            }
        } catch (SocketException e) {
            log.error("获取服务器ip异常.", e);
        }
        return ip;
    }
}

reference

java gets the real ip of the server

Guess you like

Origin blog.csdn.net/yxz8102/article/details/112239586