Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw new exceptions for pretend URL address

I've made something that retrieves the IP address of a URL I typed in.

InetAddress ip = InetAddress.getByName("www.fake.cao");
return ia.getHostAddress();

I've also thrown UnknownHostException to try catch the error for incorrect URL's.

The problem is, www.fake.cao is recognised as a genuine URL and returns me a unavailable IP address, and doesn't throw an exception.

Can anyone tell me what can I do to catch these pretentious URL's?

like image 892
Dembele Avatar asked Mar 17 '13 22:03

Dembele


2 Answers

The issue is that your ISP returns a fake page for a non existent DNS domain. That (bad) practice is known as NXDOMAIN redirection.

The JRE cannot tell whether 81.200.64.50 is the actual IP address of www.fake.cao, or it is a fake page injected by your ISP.

Other than actually trying to open a socket and check whether it connects (note that it could connect even if the host does not exist, for instance, if you try to open an HTTP connection), you might compare the returned IP for that host, with the returned IP of an already known to be invalid host (such as does-not-exist.invalid).

InetAddress ip = InetAddress.getByName("www.fake.cao");

InetAddress fake;
try {
   fake = InetAddress.getByName("does-not-exist.invalid");      
} catch (UnknownHostException e) {
   //www.fake.cao exists, but invalid does not
   return ip;
} 
if (Arrays.equals(ip.getAddress(),fake.getAddress())) {
    //both ip and fake resolves to the same IP
    throw new UnknownHostException();
}

//invalid does exist, but it is different from ip
return ip;

This approach isn't complete, because your ISP might be returning different addresses for different non-existent hosts, but at least tries to address the issue.

like image 121
Javier Avatar answered Sep 22 '22 13:09

Javier


Attempt to open a socket to the address, that will throw an exception if the address is invalid.

like image 32
Chris Cooper Avatar answered Sep 23 '22 13:09

Chris Cooper