バックグラウンド
以前にアラートメールを作成しました。一部のビジネスシナリオでは、プログラムの実行に失敗した場合にアラートメールを開発者に送信する必要があります。同じ環境に複数のサーバーがあるため、問題のトラブルシューティングを迅速に行うために、マシンのIPを電子メールヘッダーに追加したいと思います。
成し遂げる
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;
}
}