Java network programming recognition example gets a list of host network interfaces

  • 2020-04-01 02:51:00
  • OfStack


Gets the host address information

In Java we use the InetAddress class to represent the target network address, including the address information of hostname and numeric type, and the instances of InetAddress are immutable, each instance always pointing to an address. The InetAddress class contains two subclasses corresponding to the versions of two IP addresses:


Inet4Address
Inet6Address

We know from the previous notes that IP addresses are actually assigned to the connection between the host and the network, not the host itself, and that the NetworkInterface class provides access to information about all of the host's interfaces. Here's how to get the address information of a web host using a simple example program:


importjava.net.*;
importjava.util.Enumeration;
publicclassInetAddressExample{
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
try{
//Gets a list of host network interfaces
Enumeration<NetworkInterface>interfaceList=NetworkInterface
.getNetworkInterfaces();
//Detect if the list of interfaces is empty, and the loopback interface should exist even if the host does not have any other network connections
if(interfaceList==null){
System.out.println("-- No found interface --");
}else{
while(interfaceList.hasMoreElements()){
//Gets and prints the address of each interface
NetworkInterfaceiface=interfaceList.nextElement();
//Print interface name
System.out.println("Interface"+iface.getName()+";");
//Gets the address associated with the interface
Enumeration<InetAddress>addressList=iface
.getInetAddresses();
//Whether is empty
if(!addressList.hasMoreElements()){
System.out.println("t( There is no address associated with this interface )");
}
//Iteration of the list, printing out each address
while(addressList.hasMoreElements()){
InetAddressaddress=addressList.nextElement();
System.out
.print("tAddress"
+((addressinstanceofInet4Address?"(v4)"
:addressinstanceofInet6Address?"v6"
:"(?)")));
System.out.println(":"+address.getHostAddress());
}
}
}
}catch(SocketExceptionse){
System.out.println(" Error getting network interface :"+se.getMessage());
}
//Gets the hostname and address for each parameter entered from the command line, iterates the list, and prints it
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("t Unable to find address :"+host);
}
}
}
}


Related articles: