简体   繁体   中英

Java - Get IP address by name DNS (?)

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?)

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.

Usually, clients should connect to server by DNS, not by IP. Just configure your clients to connect to example.com and configure the DNS name example.com to point to your IP address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM