获取本机IP
来源:互联网 发布:二手交易软件排名 编辑:程序博客网 时间:2024/05/16 17:30
packagecom.dangdang.ddframe.job.internal.env;
importjava.net.InetAddress;
importjava.net.NetworkInterface;
importjava.net.SocketException;
importjava.net.UnknownHostException;
importjava.util.Enumeration;
importcom.dangdang.ddframe.job.exception.JobException;
/**
* 获取真实本机网络的服务.
*
*@authorzhangliang
*/
publicclassLocalHostService {
privatestaticvolatileStringcachedIpAddress;
/**
* 获取本机IP地址.
*
*<p>
* 有限获取外网IP地址.
* 也有可能是链接着路由器的最终IP地址.
*</p>
*
*@return本机IP地址
*/
publicString getIp() {
if(null!=cachedIpAddress) {
returncachedIpAddress;
}
Enumeration<NetworkInterface> netInterfaces;
try{
netInterfaces = NetworkInterface.getNetworkInterfaces();
}catch(finalSocketException ex) {
thrownewJobException(ex);
}
String localIpAddress =null;
while(netInterfaces.hasMoreElements()) {
NetworkInterface netInterface = netInterfaces.nextElement();
Enumeration<InetAddress> ipAddresses = netInterface.getInetAddresses();
while(ipAddresses.hasMoreElements()) {
InetAddress ipAddress = ipAddresses.nextElement();
if(isPublicIpAddress(ipAddress)) {
String publicIpAddress = ipAddress.getHostAddress();
cachedIpAddress= publicIpAddress;
returnpublicIpAddress;
}
if(isLocalIpAddress(ipAddress)) {
localIpAddress = ipAddress.getHostAddress();
}
}
}
cachedIpAddress= localIpAddress;
returnlocalIpAddress;
}
privatebooleanisPublicIpAddress(finalInetAddress ipAddress) {
return!ipAddress.isSiteLocalAddress() && !ipAddress.isLoopbackAddress() && !isV6IpAddress(ipAddress);
}
privatebooleanisLocalIpAddress(finalInetAddress ipAddress) {
returnipAddress.isSiteLocalAddress() && !ipAddress.isLoopbackAddress() && !isV6IpAddress(ipAddress);
}
privatebooleanisV6IpAddress(finalInetAddress ipAddress) {
returnipAddress.getHostAddress().contains(":");
}
/**
* 获取本机Host名称.
*
*@return本机Host名称
*/
publicString getHostName() {
returngetLocalHost().getHostName();
}
privatestaticInetAddress getLocalHost() {
InetAddress result;
try{
result = InetAddress.getLocalHost();
}catch(finalUnknownHostException ex) {
thrownewJobException(ex);
}
returnresult;
}
}
阅读全文
0 0
- 获取本机IP
- 获取本机IP
- 获取本机IP
- 获取本机IP
- 获取本机ip
- 获取本机IP
- 获取本机ip
- 获取本机ip
- 获取本机IP
- 获取本机IP
- 获取本机IP
- 获取本机ip
- 获取本机ip
- 获取本机Ip
- 获取本机 ip
- 获取本机ip
- 获取本机IP
- 获取本机ip
- matlab2c使用c++实现matlab函数系列教程-max函数
- BZOJ3259(莫比乌斯反演 + 树状数组 + 离散处理 + 极性函数)
- matlab2c使用c++实现matlab函数系列教程-min函数
- sublime的下载地址及Package Control的安装
- jquery-DOM操作
- 获取本机IP
- matlab2c使用c++实现matlab函数系列教程-mean函数
- Kafka 实例
- matlab2c使用c++实现matlab函数系列教程-median函数
- Tyvj1078
- 1029:求矩阵的两对角线上的元素之和
- stdio.h及cstdio的区别
- [HDU](2187)悼念512汶川大地震遇难同胞——老人是真饿了 ---贪心
- 获得键盘方向键VC++