Java Program to Determine Hostname from IP Address
Last Updated :
09 Nov, 2020
IP Address stands for internet protocol address. It is an identifying number that is associated with a specific computer or computer network. IP addresses are usually written and displayed in human-readable notation such as 192.168.1.35 in IPv4(32-bit IP address). When connected to the internet, the IP address allows the computers to send and receive information. Every site has its own host link to their own IP Address which helps to send the request by the user to the HTTP traffic and helps to collect the information which the users want This is how an IP address is necessary for every host.
There are many ways to get the IP Address of a particular host. So the method which helps to get the IP address for any Host is getHostAddress() of InetAddress class.
Syntax:
public String getHostAddress()
Returns: It returns the raw IP address in a string format.
Note: It is easy to find the IP Address from a Hostname. But due to security reasons, it is difficult to get the Host Name from the IP address because all IP addresses are secured.
The following methods are used to get the Host Name.
- getHostName(): This function retrieves the standard hostname for the local computer.
- getHostByName(): This function retrieves host information corresponding to a hostname from a host database.
Example: Obtaining the IP address from the given host
Java
import java.io.*;
import java.util.*;
import java.net.*;
class GFG {
public static void main(String[] args)
{
String host = "www.geeksforgeeks.org" ;
try {
InetAddress[] iaddress
= InetAddress.getAllByName(host);
for (InetAddress ipaddresses : iaddress) {
System.out.println(ipaddresses.toString());
}
}
catch (UnknownHostException e) {
System.out.println(e);
}
}
}
|
Example: Obtaining the Hostname from the Given IP address. All the Server and IP are Secured for a security reason So Hostname directly from the IP address cannot be found. But the Method is similar to found any Hostname from the unsecured IP address.
Java
import java.io.*;
import java.net.*;
class GFG {
public static void main(String[] args)
{
try {
InetAddress addr
= InetAddress.getByName( "23.229.203.68" );
System.out.println( "Host name is: "
+ addr.getHostName());
System.out.println( "Ip address is: "
+ addr.getHostAddress());
}
catch (UnknownHostException e) {
System.out.println(e);
}
}
}
|
Output
Host name is: 23.229.203.68
Ip address is: 23.229.203.68
Share your thoughts in the comments
Please Login to comment...