java获取ip地址与网络接口的方法示例

2025-05-29 0 61

java.net包

大家应该都知道,网络相关对象在java.net包中,java net包下的类如下:

java获取ip地址与网络接口的方法示例

java获取ip地址与网络接口的方法示例

1.获取主机对象inetaddress

?

1

2

3

4

5
//获取本地主机对象

inetaddress host = inetaddress.getlocalhost();

//根据ip地址或主机名获取主机对象,以主机名获取主机时需要dns解析

inetaddress host = inetaddress.getbyname("192.168.100.124");

inetaddress host = inetaddress.getbyname(www.baidu.com);

2.获取主机对象的ip地址和主机名(需要dns解析主机名)

?

1

2
host.gethostaddress();

host.gethostname();

3.获取本机所有接口networkinterface并遍历

?

1

2

3

4

5

6
//返回数据类型为enumeration

enumeration<networkinterface> enu = networkinterface.getnetworkinterfaces();

while(enu.hasmoreelements){

networkinterface inet = enu.nextelement();

string intname = inet.getname();

}

由于一个接口上可能有多个子接口(辅助ip,如eth0:1),因此根据某个接口,可以得到该接口的所有ip地址枚举集合(同时包括ipv4和ipv6接口)。

?

1

2

3

4

5
enumeration<inetaddress> net_list = inet.getinetaddresses();

while(net_list.hasmoreelements){

inetaddress net = net_list.nextelement();

string ip = net.gethostaddress();

}

可以使用collections.list()方法将enumeration类型转换为arraylist集合的数据结构,然后使用itreator遍历器遍历。

以下是获取本机所有接口名称和这些接口上的ipv4地址的方法(适用于windows和linux)。

?

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
import java.net.*;

import java.util.*;

public class enumdemo {

public static void main(string[] args) {

try {

//获取所有接口,并放进枚举集合中,然后使用collections.list()将枚举集合转换为arraylist集合

enumeration<networkinterface> enu = networkinterface.getnetworkinterfaces();

arraylist<networkinterface> arr = collections.list(enu);

for(iterator<networkinterface> it = arr.iterator();it.hasnext();) {

networkinterface ni = it.next();

string intname = ni.getname(); //获取接口名

//获取每个接口中的所有ip网络接口集合,因为可能有子接口

arraylist<inetaddress> inets = collections.list(ni.getinetaddresses());

for(iterator<inetaddress> it1 = inets.iterator();it1.hasnext();) {

inetaddress inet = it1.next();

//只筛选ipv4地址,否则会同时得到ipv6地址

if(inet instanceof inet4address) {

string ip = inet.gethostaddress();

system.out.printf("%-10s %-5s %-6s %-15s\\n", "inetfacename:",intname,"| ipv4:",ip);

}

}

}

} catch (socketexception s) {

s.printstacktrace();

}

}

}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对快网idc的支持。

原文链接:https://www.cnblogs.com/f-ck-need-u/p/8243496.html

收藏 (0) 打赏

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

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

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

快网idc优惠网 建站教程 java获取ip地址与网络接口的方法示例 https://www.kuaiidc.com/113006.html

相关文章

发表评论
暂无评论