java.net包
大家应该都知道,网络相关对象在java.net包中,java net包下的类如下:
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
相关文章
猜你喜欢
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-29 39
-
2025-05-29 31
-
2025-05-29 67
-
2025-05-29 51
-
2025-05-29 103
热门评论



