Search code examples
javanetwork-programmingip-address

Get IP of a specific host is not working over a network with Java


I'm not able to get IP of hostname over a network. I can get public IP but seems not to work over a network because of missing protocol:

public static void main(String[] args) throws UnknownHostException {

    String url = "host22.my.network";
    getIp(url);
}

public static void getIp(String url) throws UnknownHostException{

    try { 
        InetAddress ip = InetAddress.getByName(new URL(url).getHost()); 
        System.err.println(ip);
    } 
    catch (MalformedURLException e) { 
        System.err.println(e.getMessage());
    }
}

maybe it's missing a protocol prefix


Solution

  • Since @ejp doesn't want to actually answer questions any more, here's what he's saying:

    new URL(url).getHost() is wrong. Instead, use

    InetAddress ip = InetAddress.getByName(url)
    

    And since you're not actually passing a URL, rename the parameter to hostname.