获取请求ip的工具类
2016-03-28 12:46
183 查看
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
private static String getIP() {
String localip = null;// 本地IP,如果没有配置外网IP则返回它
String netip = null;// 外网IP
try {
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
localip = ip.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
if (netip != null && !"".equals(netip)) {
return netip;
} else {
return localip;
}
}
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
private static String getIP() {
String localip = null;// 本地IP,如果没有配置外网IP则返回它
String netip = null;// 外网IP
try {
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
localip = ip.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
if (netip != null && !"".equals(netip)) {
return netip;
} else {
return localip;
}
}
相关文章推荐
- 飛飛(十二) 求两个数的最大公约数。
- Scala: forSome关键字
- 数据结构 - 求二叉树中结点的最大距离(C++)
- 75. Sort Colors
- 字典
- 2016年的前端技术栈展望
- B+ 树
- [树莓派2]--系统的安装
- [better practice系列]Android中更舒服的使用log
- jQuery筛选
- Node.js intro
- Python - Http Get Post请求
- Python数据分析-索引和选择数据
- 今天开博
- Oracle、MySql数据分页查询
- 用10张图来看机器学习Machine learning in 10 pictures
- 给出一个数字m,求满足m = a^3 + b^3(a,b为正整数)的所有整数对(分解素因子防超时)
- 三种经典iPhone上网络抓包方法详解
- c++实验2-标准体重
- B- 树