Java - Get IP address by DNS name (?)

My problem is this:

I have a java program, a server, waiting for TCP connections from clients. The fact is that the IP address that the server uses to wait for connections can change over time ... Therefore, I want clients to be able to somehow obtain this address. I think I need to set up some kind of DNS server, but I don’t know exactly how to do this. If there is such a service for free, etc.

So, I think, then it will work as follows: the server gets its IP address at startup. Then contact the DNS service (?) To set this IP address. So, the clients do something like getByName and see that the IP address of the server establishes a connection.
will it be so? If so, how is this done on the java server code and which DNS service can I use (and how to configure it?)

+4
source share
2 answers

If your Java application is running on a computer on the Internet, it already has DNS, and it already has at least one IP address visible to other computers on your local network. 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 address of the machine on which you run the Java server application changes (it works on the home computer, and the ISP assigns a dynamic IP address), then use a free service, for example http://www.dyndns.com or the like . In this case, it becomes a bit complicated because you have to report a change in the dynamic IP DNS. Some routers have a built-in feature, some do not. In this case, you must ensure that dynamicDNS is informed. There are many scripts on the Internet that do this for you (usually Linux / UNIX), and there are also some free Windows tools. I never did this on Windows, but I did it on Linux, and it works well.

+3
source

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

-1
source

Source: https://habr.com/ru/post/1386495/


All Articles