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.
- 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.
- 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); |
No comments:
Post a Comment