Get host address information
In Java, we use the InetAddress class to represent the target network address, including host name and numeric address information, and instances of InetAddress are immutable, and each instance always points to an address. The InetAddress class contains two subclasses, corresponding to the two IP address versions:
Copy the code code as follows:
Inet4Address
Inet6Address
We can know from the previous notes: IP addresses are actually assigned to the connection between the host and the network, rather than the host itself. The NetworkInterface class provides the function of accessing information on all interfaces of the host. Below we use a simple example program to learn how to obtain the address information of a network host:
Copy the code code as follows:
importjava.net.*;
importjava.util.Enumeration;
publicclassInetAddressExample{
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
try{
//Get the host network interface list
Enumeration<NetworkInterface>interfaceList=NetworkInterface
.getNetworkInterfaces();
//Check whether the interface list is empty. Even if the host does not have any other network connections, the loopback interface (loopback) should exist.
if(interfaceList==null){
System.out.println("--No interface found--");
}else{
while(interfaceList.hasMoreElements()){
//Get and print the address of each interface
NetworkInterfaceiface=interfaceList.nextElement();
//Print interface name
System.out.println("Interface"+iface.getName()+";");
//Get the address associated with the interface
Enumeration<InetAddress>addressList=iface
.getInetAddresses();
//Whether it is empty
if(!addressList.hasMoreElements()){
System.out.println("/t(There is no address related to this interface)");
}
//Iteration of the list, print out each address
while(addressList.hasMoreElements()){
InetAddressaddress=addressList.nextElement();
System.out
.print("/tAddress"
+((addressinstanceofInet4Address?"(v4)"
:addressinstanceofInet6Address?"v6"
:"(?)")));
System.out.println(":"+address.getHostAddress());
}
}
}
}catch(SocketException){
System.out.println("Get network interface error:"+se.getMessage());
}
//Get the host name and address corresponding to each parameter entered from the command line, iterate the list and print
for(Stringhost:args){
try{
System.out.println(host+":");
InetAddress[]addressList=InetAddress.getAllByName(host);
for(InetAddressaddress:addressList){
System.out.println("/t"+address.getHostName()+"/"
+address.getHostAddress());
}
}catch(UnknownHostExceptione){
System.out.println("/tUnable to find address:"+host);
}
}
}
}