Search code examples
javainetaddressunknown-host

inetAddress.getByName(address) unknownhostexception


Does the getByName() function work on a link with a path like https://stackoverflow.com/questions, or does the link have to include the host only (https://stackoverflow.com)?

I get UnknownHostException when I use a link that contains a "/", any tips on how to resolve that?

The console says the error lies here:

socket = new Socket(InetAddress.getByName(adr), port);

Solution

  • InetAddress.getByName looks up a name (usually in DNS) and returns the corresponding address.

    There's no host called "https://stackoverflow.com/questions" so that throws an UnknownHostException.
    There's no host called "https://stackoverflow.com" either.
    In this particular example, the host name is "stackoverflow.com".

    If you want to parse a URL (such as "https://stackoverflow.com/questions") to get the hostname, you can use the java.net.URL class:

    String hostname = new URL("https://stackoverflow.com/questions").getHost();
    System.out.println(hostname); // stackoverflow.com