Get host address information
In Java we use the InetAddress class to represent the destination network address, including the host name and numeric type address information, and the InetAddress instance is immutable, and each instance always points to an address. The InetAddress class contains two subclasses, corresponding to the two version of the IP address:
Copy Code code as follows:
Inet4address
Inet6address
We know from the previous notes that the IP address is actually assigned to the connection between the host and the network, rather than the host itself, the NetworkInterface class provides the ability to access information about all the interfaces of the host. Here's a simple example program to learn how to get address information for a network host:
Copy Code code as follows:
importjava.net.*;
Importjava.util.Enumeration;
publicclassinetaddressexample{
Publicstaticvoidmain (String[]args) {
Todoauto-generatedmethodstub
try{
Get a list of host network interfaces
Enumeration<networkinterface>interfacelist=networkinterface
. Getnetworkinterfaces ();
Detects if the interface list is empty, and the loopback interface (loopback) should exist even if the host does not have any other network connections
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 () + ";");
Gets the address associated with the interface
Enumeration<inetaddress>addresslist=iface
. getinetaddresses ();
is empty
if (!addresslist.hasmoreelements ()) {
System.out.println ("t (no address associated with 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 (socketexceptionse) {
SYSTEM.OUT.PRINTLN ("Get Network Interface Error:" +se.getmessage ());
}
Gets the host name and address of each parameter entered from the command line, iterates over the list, and prints
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 cannot find address:" +host);
}
}
}
}