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

2025-05-29 0 65

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

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

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

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

获取本地的Ip地址:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30
/**

* 获取服务器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完成读取操作,但本质仍然是前台界面的读取。

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

原文链接:http://www.cnblogs.com/george93/p/6306579.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java中获取当前服务器的Ip地址的方法 https://www.kuaiidc.com/118754.html

相关文章

发表评论
暂无评论