Anirudha Mahadik
Anirudha Mahadik

Reputation: 53

How to get URL from an IP address in Java?

I found code to fetch host name from IP address. The code is some what like shown below:

import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetHostName{
    public static void main(String a[]){
        try{
            InetAddress host = InetAddress.getByName("74.125.68.94");
            System.out.println(host.getHostName());
        }
        catch(UnknownHostException ex){
            ex.printStackTrace();
        }
    }
}

It shows output like:

sc-in-f94.1e100.net

But when i fired this IP address (74.125.68.94) through the browser it opens up Google website. So my question is how can i fecth URL like http://www.google.com from an IP address rather than displaying sc-in-f94.1e100.net using java?

Upvotes: 2

Views: 3278

Answers (2)

Prim
Prim

Reputation: 2978

You can't do that.

Usually, several domains can be reach on same IP. You can just identify the hostname like you already do. This is the name of the machine, equivalent to the IP, which serves the domain.

Moreover, an IP is just an address of a machine which also can serve any domain because it can be a web server or not.

Upvotes: 4

mehrdadjg
mehrdadjg

Reputation: 384

You are actually doing everything right. The thing is that today many host names can live on the same server. This way you can easily convert the host name to the IP address of the server but when you attempt to do the reverse, you only get the name of the server which is in this case sc-in-f94.1e100.net.

Here is an excerpt from hcidata:

In the early years of the Internet, each sub-domain would have a unique IP address so it was common for a host machine to have only one sub domain name. Nowadays, the common practice is to have many sub-domains with the same IP address. It is also common for the domain name to be converted to the IP address of the host machine that runs the www sub domain.

I hope this will clear things up for you.

Upvotes: 1

Related Questions