Last Updated on 18 July 2019   |   Print Email
This article helps you understand InetAddress- a fundamental class in Java Network API.The InetAddress class represents an IP address, both IPv4 and IPv6. Basically you create instances of this class to use with other classes such as Socket, ServerSocket, DatagramPacket and DatagramSocket. In the simplest case, you can use this class to know the IP address from a hostname, and vice-versa.The InetAddress class doesn’t have public constructors, so you create a new instance by using one of its factory methods:
getByName(String host): creates an InetAddress object based on the provided hostname.
getByAddress(byte[] addr): returns an InetAddress object from a byte array of the raw IP address.
getAllByName(String host): returns an array of InetAddress objects from the specified hostname, as a hostname can be associated with several IP addresses.
getLocalHost(): returns the address of the localhost.
To get the IP address/hostname you can use a couple of methods below:
getHostAddress(): returns the IP address in text.
getHostname(): gets the hostname.
Note that the InetAddress class’s toString() method returns both hostname and IP address, e.g. www.codejava.net/198.57.151.22.In addition, this class also provides several methods for checking the address type, which would be useful for system programmers. However we don’t have to concern about those methods, most of the time.
Let’s see some examples that demonstrate how to use the InetAddress class.
Get IP address of a given domain/hostname:
The following code prints the IP address of a given hostname:
These are subclasses of the InetAddress class. Inet4Address and Inet6Address represent IPv4 and IPv6 addresses, respectively. However, when writing network applications, you don’t have to concern about IPv4 or IPv6 as Java hides all the details.The InetAddress can refer to either Inet4Address or Inet6Address so most of the time, using InetAddress is enough.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments