I’m programming a little server example with Sockets in Java.
Currently I’m using this for testing:
server= new Socket(InetAdress.getByName("127.0.0.1"),3333)
but my plan is to move it to my Raspberry Pi.
Unfortunately, I don’t have a static IP address.
What is the proper way to update the IP address in the code?
I thought about storing it on a webserver and accessing it via an API, but that doesn’t sound very secure, and it might slow down my code.
Advertisement
Answer
First off, your use of InetAdress.getByName()
is redundant. Socket
has a constructor that accepts a String
as input:
server = new Socket("127.0.0.1", 3333)
That said, you should register a static domain name for your server, and set its DNS records to point at your server’s IP. Then clients can use that domain name to connect to the server, instead of using the IP address directly:
server = new Socket("mydomain", 3333)
If your server does not have a static IP, there are plenty of free and cheap “Dynamic DNS” services available, which allow you to update your domain with your current IP address whenever it changes (typically using automated tools to simplify the detection-and-update process).
If the server is behind a router, many routers have built-in support for updating various DynDNS services for you. If your router supports this, you can configure it with your DynDNS account information so it can automatically update the domain whenever its WAN IP changes.