码迷,mamicode.com
首页 > 编程语言 > 详细

java 获取的是本地的IP地址

时间:2018-02-01 00:24:55      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:static   index   cat   str   eth   return   trace   enum   nginx   

1 public static void main(String[] args) {
 2       try {
 3              InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
 4              String hostAddress = address.getHostAddress());//192.168.0.121            
 5              InetAddress address1 = InetAddress.getByName("www.wodexiangce.cn");//获取的是该网站的ip地址,比如我们所有的请求都通过nginx的,所以这里获取到的其实是nginx服务器的IP地 
 6              String hostAddress1 = address1.getHostAddress());//124.237.121.122 
 7              InetAddress[] addresses = InetAddress.getAllByName("www.baidu.com");//根据主机名返回其可能的所有InetAddress对象 
 8              for(InetAddress addr:addresses){ 
 9              System.out.println(addr);//www.baidu.com/14.215.177.38 
10              //www.baidu.com/14.215.177.37 
11            } 
12         } catch (UnknownHostException e) { 
13              e.printStackTrace();
14       } 
15  }


/**
* 获取服务器IP地址
* @return
*/
@SuppressWarnings("unchecked")
public static String getServerIp(){
String SERVER_IP = null;
try {
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
ip = (InetAddress) ni.getInetAddresses().nextElement();
SERVER_IP = ip.getHostAddress();
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {
SERVER_IP = ip.getHostAddress();
break;
} else {
ip = null;
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return SERVER_IP;
}
}

java 获取的是本地的IP地址

标签:static   index   cat   str   eth   return   trace   enum   nginx   

原文地址:https://www.cnblogs.com/duanqiao123/p/8395115.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!