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地址:
publicstaticvoidmain(String[]args){
try{
InetAddressaddress=InetAddress.getLocalHost();//获取的是本地的IP地址//PC-20140317PXKX/192.168.0.121
StringhostAddress=address.getHostAddress());//192.168.0.121
InetAddressaddress1=InetAddress.getByName("www.wodexiangce.cn");//获取的是该网站的ip地址,比如我们所有的请求都通过nginx的,所以这里获取到的其实是nginx服务器的IP地
StringhostAddress1=address1.getHostAddress());//124.237.121.122
InetAddress[]addresses=InetAddress.getAllByName("www.baidu.com");//根据主机名返回其可能的所有InetAddress对象
for(InetAddressaddr:addresses){
System.out.println(addr);//www.baidu.com/14.215.177.38
//www.baidu.com/14.215.177.37
}
}catch(UnknownHostExceptione){
e.printStackTrace();
}
}
获取服务器的Ip地址(其他人写的)
/**
*获取服务器IP地址
*@return
*/
@SuppressWarnings("unchecked")
publicstaticStringgetServerIp(){
StringSERVER_IP=null;
try{
EnumerationnetInterfaces=NetworkInterface.getNetworkInterfaces();
InetAddressip=null;
while(netInterfaces.hasMoreElements()){
NetworkInterfaceni=(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(SocketExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
returnSERVER_IP;
}
}
基于SSM框架的农业物联网智能养殖系统中的养殖日志要求上传一张图片到服务器中。本地测试时,由于保存的路径在本地磁盘E中,所以后台直接从本地获取了资源文件。传入服务器胡,找不到该文件,估计是IP地址无法获取到,只有对应的文件路径,基于此,想设计出从服务器里读取文件信息,但是并没有成功。后来发现localhost与127.0.0.1是一致的,就想起了用服务器IP地址代替localhost完成读取操作,但本质仍然是前台界面的读取。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。