您的位置:首页 > 编程语言 > Java开发

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

2017-02-09 11:44 891 查看

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

例子:可以通过http://localhost:8080/项目root值访问,也可以通过http://127.0.0.1/项目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完成读取操作,但本质仍然是前台界面的读取。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java ip地址