Java獲取客戶端所在的IP地址和伺服器地址
阿新 • • 發佈:2019-01-10
/** 2 * 獲取本地IP地址 3 * @return 4 */
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 }
/** 2 * 獲取伺服器IP地址 3 * @return 4 */ 5 @SuppressWarnings("unchecked") 6 public static String getServerIp(){ 7 String SERVER_IP = null; 8 try { 9 Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces(); 10 InetAddress ip = null; 11 while (netInterfaces.hasMoreElements()) { 12 NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement(); 13 ip = (InetAddress) ni.getInetAddresses().nextElement(); 14 SERVER_IP = ip.getHostAddress(); 15 if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() 16 && ip.getHostAddress().indexOf(":") == -1) { 17 SERVER_IP = ip.getHostAddress(); 18 break; 19 } else { 20 ip = null; 21 } 22 } 23 } catch (SocketException e) { 24 // TODO Auto-generated catch block 25 e.printStackTrace(); 26 } 27 28 return SERVER_IP; 29 } 30 }