java中获取当前服务器的Ip地址

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

         例子:可以通过http://localhost:8080/项目root值访问,也可以通过http://127.0.0.1/项目root值访问。

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

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

  获取本地的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地址(其他人写的)

 

 1 /**
 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 }

 

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

posted @ 2017-01-19 14:44  George93  阅读(103649)  评论(0编辑  收藏  举报