Java - Get IP address by name DNS (?)

15,303

If your Java application runs on machine that is on the Internet, it already has a DNS service available and it already has at least one IP visible by other machines in your LAN. Use Java code similar to what I wrote below to get the IP address.

import java.net.*;
import java.io.*;

public class Ip {
  public static void main ( String[] args ) throws IOException {
    String hostname = args[0];

    try {
      InetAddress ipaddress = InetAddress.getByName(hostname);
      System.out.println("IP address: " + ipaddress.getHostAddress());
    } catch ( UnknownHostException e ) {
      System.out.println("Could not find IP address for: " + hostname);
    }
  }
}

PS. if the IP of machine on which you run your Java server application is changing (it is running on a home machine and ISP assigns dynamic IP), then use a free service like http://www.dyndns.com or similar. In this case it gets little bit complicated, because you have to inform your dynamic DNS of IP change. Some routers have this feature built-in, some do not. In this case you have to make sure dynamicDNS is informed. There are bunch of scripts available on the Internet that do this for you (typically for Linux / UNIX), and there are some freeware tools for Windows. I never did this on Windows, but I did it with Linux and it works nicely.

Share:
15,303
kri8or
Author by

kri8or

Updated on August 23, 2022

Comments

  • kri8or
    kri8or over 1 year

    My issue is the following:

    I have a java program, a server, that is waiting for TCP connections from the clients. The thing is, the IP address which the server is using for waiting for connections can change with time... So I want the clients to be able to get this address in some way. I think I need to configure some DNS server, but I dont know exactly how. If there is such service for free, etc...

    So I think then it would work like this: the server when starting, gets its IP. Then access some DNS (?) service to put this IP available. So then clients make something like getByName, and see what is the IP of the server to estabilish connection.
    would it be like this? If so, how is this on the java server code, and what DNS service can I use (and how to configure it?)

  • kri8or
    kri8or over 12 years
    thank you for your answer. dyndns was what I was trying to use, I'm trying to configure it now
  • DejanLekic
    DejanLekic over 12 years
    Clients may connect to the server in various ways. Sometimes even not by any IP! (Example: UNIX domain sockets) It all depends on the design. Second, you cant easily configure DNS (if he owns it) if the IP changes (and obviously does, judging from the OP). Furthermore, sometimes you know beforehand that the IP of your server is going to be static, but the hostname perhaps may not be setup.