zoukankan      html  css  js  c++  java
  • java 获取的是本地的IP地址

    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;
    }
    }

  • 相关阅读:
    springboot scheduled多线程
    Oracle sql 小数点前面0不显示
    (转)VIM常用命令集锦
    java 面试题
    关于oracle start with connect by 全表扫描的一点想法
    (转)window.opener方法的使用 刷新父页面
    (转)jQuery “not readonly” selector
    (转)jquery合并单元格
    Java 格式化json为json树
    我的2018
  • 原文地址:https://www.cnblogs.com/duanqiao123/p/8395115.html
Copyright © 2011-2022 走看看