package net.junnan.religious.peixun.api.util;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Enumeration;
/**
* IP地址Util
*/
@Slf4j
public class IpAddressUtil {
public static InetAddress getLocalHostLANAddress() throws UnknownHostException {
try {
InetAddress candidateAddress = null;
// 遍历所有的网络接口
for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
// 在所有的接口下再遍历IP
for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
if (inetAddr.isSiteLocalAddress()) {
// 如果是site-local地址,就是它了
return inetAddr;
} else if (candidateAddress == null) {
// site-local类型的地址未被发现,先记录候选地址
candidateAddress = inetAddr;
}
}
}
}
if (candidateAddress != null) {
return candidateAddress;
}
// 如果没有发现 non-loopback地址.只能用最次选的方案
InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
if (jdkSuppliedAddress == null) {
throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
}
return jdkSuppliedAddress;
} catch (Exception e) {
UnknownHostException unknownHostException = new UnknownHostException(
"Failed to determine LAN address: " + e);
unknownHostException.initCause(e);
throw unknownHostException;
}
}
public static String getOutIP() {
try {
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
String ip = in.readLine();
return ip;
// System.out.println("Public IP Address: " + ip);
} catch (Exception e) {
// System.out.println("Error occurred: " + e.getMessage());
}
return "";
}
}
获取公网ip
原创
©著作权归作者所有:来自51CTO博客作者想买CT5的小曹的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
获取IP地址
端点(API接口)访问获取IP地址!
IP Java SpringBoot\ -
python 获取公网IP
python 获取公网IP
json python IP -
C#:获取公网IP
C#获取公网IP
html json 接口实现 编程 -
plc数据类型 对应java
1. 数据类型在PLC项目编程中,离不开数据类型和变量,搞清楚数据类型和数据类型的转换很重要。常用的数据类型包括以下几种:位(bit),字节(Byte),字(Word),双字(Double Word),整型数(INT),双整型书(DINT),及实数/浮点数(Real)1.1 位(bit)常称作布尔量BOOL,在高级语言中,会说布尔变量,布尔控件等。取值:0 ,1寻址:I0.0 M0.0 Q0.0
plc数据类型 对应java byte是什么数据类型 int数据类型范围 表示int数据类型的数据范围 寻址