InetAddress以及InetSocketAddress
InetAddress是一个Java中的类,这个类种有很多方法,且这些方法都是静态的,因此可以利用类直接进行引用。这个类是封装Ip的,可以获得本机的ip以及本机的主机名,同时这个类支持将将域名转换。而相对的InetSocketAddress是封装ip以及端口的,这个类是有构造函数的,而InnetAddress是不存在构造函数的,而InetSocketAddress的构造函数的属性存在有(String hostname, InetAddress addr, int port)等属性的。其实很简单,就是两个工具类…
public class Main {
public static void main(String[] args) {
net();
}
//比对InetAddress以及InetSocketAddress
public static void net(){
//InetAddress是封装IP的
try {//本机操作
InetAddress address = InetAddress.getLocalHost();
String ip =address.getHostAddress();
String hostName = address.getHostName();
System.out.println("本机ip是:"+ip+" "+"主机名"+hostName);
//基于域名封装ip
address=InetAddress.getByName("www.baidu.com");
ip =address.getHostAddress();
hostName = address.getHostName();
System.out.println("百度ip是:"+ip+" "+"主机名"+hostName);
//封装InetSocketAddress
InetSocketAddress socketAddress=new InetSocketAddress(InetAddress.getLocalHost(),8888);
System.out.println(socketAddress.getAddress().getHostAddress());
System.out.println(socketAddress.getAddress().getHostName());
System.out.println(socketAddress.getPort());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
但是我发现,每个主机有很多的网卡,不同的网卡对应不同的IP,我想全部拿到怎么办呢?
NetworkInterface
查资料,查到,可以利用另一个工具类NetworkInterface…尝试着看一下源码,看一下是干啥子的…
NetworkInterface(String name, int index, InetAddress[] addrs) {
//一个网络接口存在很多的InetAddress
this.name = name;
this.index = index;
this.addrs = addrs;
}
//获得获得该网卡绑定的所有IP地址
public Enumeration<InetAddress> getInetAddresses() {..}
//获得当前机器的所有网络接口(所有网卡)
public java.util.List<InterfaceAddress> getInterfaceAddresses() {...}
public static void getAllNet(){
try {
//获得该机器上所有的网卡
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
//Enumeration是一个继承迭代器的类,有hasMoreElements()以及nextElement()
while (networkInterfaces.hasMoreElements()){
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()){
InetAddress address = inetAddresses.nextElement();
System.out.println("网卡名称:"+networkInterface.getName()+" "+"IP地址:"+address.getHostAddress());
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}