The InetAddress class is a class used in Java to describe an IP address. It's in the java.net package. In Java, the addresses of IPV4 and IPV6 are described separately using inet4address and Inet6address classes. These two classes are all inetaddress subclasses. Because InetAddress does not have a public construction method, you must rely on its four static methods to create a InetAddress object. InetAddress can get the InetAddress object of this machine by Getlocalhost method, and can also get the Getallbyname object of remote host through Getbyname, Getbyaddress and InetAddress.
First, Getlocalhost method
Use Getlocalhost to get a InetAddress object that describes native IP. This method is defined as follows:
public static inetaddress Getlocalhost () throws Unknownhostexception
This method throws a Unknownhostexception exception, so the exception must be caught or thrown in the program that called the method. The following code shows how to use Getlocalhost to get the IP and computer name of this machine.
package inet;
import java.net.*;
public class MyInetAddress1
{
public static void main(String[] args) throws Exception
{
InetAddress localAddress = InetAddress.getLocalHost();
System.out.println(localAddress);
}
}
Run Result:
ComputerName/192.168.18.10
The object class's ToString method is overridden in the InetAddress class, implemented as follows:
public String toString()
{
return ((hostName != null) ? hostName : "") + "/" + getHostAddress();
}
As you can see from the code above, the ToString method in the InetAddress method returns the host name and IP address separated by "/". Therefore, the native computer name and IP address are output directly through the LocalAddress object in the above code (after passing the object parameter to the Println method, the Println method invokes the object parameter's ToString method to output the result).
When the native binds more than one IP, getlocalhost only returns the first IP. If you want to return all of the IP on this computer, you can use the Getallbyname method.