java.net包
大家應(yīng)該都知道,網(wǎng)絡(luò)相關(guān)對(duì)象在java.net包中,java net包下的類如下:
1.獲取主機(jī)對(duì)象inetaddress
1
2
3
4
5
|
//獲取本地主機(jī)對(duì)象 inetaddress host = inetaddress.getlocalhost(); //根據(jù)ip地址或主機(jī)名獲取主機(jī)對(duì)象,以主機(jī)名獲取主機(jī)時(shí)需要dns解析 inetaddress host = inetaddress.getbyname( "192.168.100.124" ); inetaddress host = inetaddress.getbyname(www.baidu.com); |
2.獲取主機(jī)對(duì)象的ip地址和主機(jī)名(需要dns解析主機(jī)名)
1
2
|
host.gethostaddress(); host.gethostname(); |
3.獲取本機(jī)所有接口networkinterface并遍歷
1
2
3
4
5
6
|
//返回?cái)?shù)據(jù)類型為enumeration enumeration<networkinterface> enu = networkinterface.getnetworkinterfaces(); while (enu.hasmoreelements){ networkinterface inet = enu.nextelement(); string intname = inet.getname(); } |
由于一個(gè)接口上可能有多個(gè)子接口(輔助ip,如eth0:1),因此根據(jù)某個(gè)接口,可以得到該接口的所有ip地址枚舉集合(同時(shí)包括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類型轉(zhuǎn)換為arraylist集合的數(shù)據(jù)結(jié)構(gòu),然后使用itreator遍歷器遍歷。
以下是獲取本機(jī)所有接口名稱和這些接口上的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 { //獲取所有接口,并放進(jìn)枚舉集合中,然后使用collections.list()將枚舉集合轉(zhuǎn)換為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(); //獲取接口名 //獲取每個(gè)接口中的所有ip網(wǎng)絡(luò)接口集合,因?yàn)榭赡苡凶咏涌?/code> arraylist<inetaddress> inets = collections.list(ni.getinetaddresses()); for (iterator<inetaddress> it1 = inets.iterator();it1.hasnext();) { inetaddress inet = it1.next(); //只篩選ipv4地址,否則會(huì)同時(shí)得到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(); } } } |
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)服務(wù)器之家的支持。
原文鏈接:https://www.cnblogs.com/f-ck-need-u/p/8243496.html