qq_36706820
2017-09-04 07:37请问一下有谁知道用Java 怎么获取Linux的外网IP
这是我的代码
public static String getRealIp() throws SocketException {
String localip = null;// 本地IP,如果没有配置外网IP则返回它
String netip = null;// 外网IP
Enumeration<NetworkInterface> netInterfaces =
NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
boolean finded = false;// 是否找到外网IP
while (netInterfaces.hasMoreElements() && !finded) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
ip = address.nextElement();
if (!ip.isSiteLocalAddress()
&& !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {// 外网IP
netip = ip.getHostAddress();
finded = true;
break;
} else if (ip.isSiteLocalAddress()
&& !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {// 内网IP
localip = ip.getHostAddress();
}
}
}
if (netip != null && !"".equals(netip)) {
return netip;
} else {
return localip;
}
}
- 点赞
- 回答
- 收藏
- 复制链接分享
1条回答
为你推荐
- Dubbo服务部署到服务器上,从本地访问服务器上的服务访问不通
- linux
- java
- 2个回答
- python中tornado的使用问题
- python
- linux
- 服务器
- tornado
- 2个回答
- JavaWeb项目部署到Linux服务器无法正常访问
- linux
- 浏览器
- java
- 阿里云
- 服务器
- 3个回答
- redisCluster Too many Cluster redirections 问题
- 集群
- sql
- redis
- 3个回答