Home  >  Article  >  Java  >  java中获取当前服务器的Ip地址的代码实例详细介绍

java中获取当前服务器的Ip地址的代码实例详细介绍

黄舟
黄舟Original
2017-03-08 11:03:053197browse

本篇文章主要介绍了java中获取当前服务器的Ip地址的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

1、tomcat是一款免费的开源Web服务器,如果部署在本地,那么对应的那么为localhost,对应地址为127.0.0.1。

例子:可以通过http://www.php.cn/:8080/项目root值访问,也可以通过http://www.php.cn/项目root值访问。

如果部署在服务器(linux)系统类,则需要通过服务器的Ip地址进行访问。

2、下面说说怎么获取Ip地址:

获取本地的Ip地址:

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

获取服务器的Ip地址(其他人写的)

/**
   * 获取服务器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;
  }
}

基于SSM框架的农业物联网智能养殖系统中的养殖日志要求上传一张图片到服务器中。本地测试时,由于保存的路径在本地磁盘E中,所以后台直接从本地获取了资源文件。传入服务器胡,找不到该文件,估计是IP地址无法获取到,只有对应的文件路径,基于此,想设计出从服务器里读取文件信息,但是并没有成功。后来发现localhost与127.0.0.1是一致的,就想起了用服务器IP地址代替localhost完成读取操作,但本质仍然是前台界面的读取。


The above is the detailed content of java中获取当前服务器的Ip地址的代码实例详细介绍. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]