Tuesday, March 3, 2020

Java InetAddress Examples

https://www.codejava.net/java-se/networking/java-inetaddress-examples


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 SocketServerSocketDatagramPacket 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.

Get IP address of a given domain/hostname:

The following code prints the IP address of a given hostname:
1
2
InetAddress address1 = InetAddress.getByName("www.codejava.net");
System.out.println(address1.getHostAddress());
 

Get hostname from IP address:

The following code finds out the hostname from an IP address:
1
2
InetAddress address2 = InetAddress.getByName("8.8.8.8");
System.out.println(address2.getHostName());
 

List all IP addresses associate with a hostname/domain:

The following code prints all the IP addresses associated with the hostname google.com:
1
2
3
4
5
InetAddress[] google = InetAddress.getAllByName("google.com");
 
for (InetAddress addr : google) {
    System.out.println(addr.getHostAddress());
}
 

Get the localhost address:

And the following code gets the localhost address:
1
2
InetAddress localhost = InetAddress.getLocalHost();
System.out.println(localhost);
 

Inet4Address and Inet6Address:

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.

No comments:

Post a Comment

Configure LOG4J in INTELLIJ in Windows.

IntelliJ debugger for temporary logging In this video, it is shown how to use Log4j in Intellij. Sorry for the audio quality :) Log4j zip fi...