4

I have a java.net.URL object in a Spring 4 @RestController. How can I check if the URL (HTTP) leads to the current machine (this Spring application) or is an URL to an external HTTP-Source?


  • I found out that java.net.URL does hostname resolution to compare to other URL object. Is there a way to reuse this resolution to not having to reinvent the wheel?
Community
  • 1
  • 1
Sebastian Barth
  • 4,079
  • 7
  • 40
  • 59

2 Answers2

8

Using the code from this post you can check if it is a local IP. You should pass an InetAddress object, so get it from your URL using the following command:

InetAddress.getByName(new URL(urlString).getHost());
Community
  • 1
  • 1
Kostas Kryptos
  • 4,081
  • 2
  • 23
  • 24
  • InetAddress.getByName(), when called on a non-numeric IP, results in a reverse DNS lookup (meaning that it goes out to network). This may be problematic in certain cases. – user1071136 Dec 07 '21 at 15:01
3

I think you can use InetAddress class to check this.

1.First get the local system IP address

      String localAddress = InetAddress.getLocalHost().getHostAddress();

2.Fetch the address of url that you want to match.

      String requestAddress = InetAddress.getByName(new URL(url).getHost()).getHostAddress();

Now you can compare both 1 and 2 address string.

I hope it helps!!!

dReAmEr
  • 6,986
  • 7
  • 36
  • 63
  • Why is your code not beeing shown as code? Tried to edit it to make that answer more awesome and failed! :) – Sebastian Barth Jan 03 '15 at 13:42
  • 1
    This wont work. localAddress returns my ip address (eg. 172.12.34.56) and requestAddress returns 127.0.0.1 Comparison will return false but they will resolve to the same address. – pmartin8 Mar 23 '18 at 15:29