英文:
What is the best way to update the ip adress of serversocket for clients?
问题
我正在使用Java编写一个小的Socket服务器示例。
目前,我正在使用以下代码进行测试:
server = new Socket(InetAddress.getByName("127.0.0.1"), 3333);
但我的计划是将其迁移到我的树莓派上。
不幸的是,我没有静态IP地址。
在代码中更新IP地址的正确方式是什么?
我考虑将其存储在Web服务器上,通过API访问,但这听起来不太安全,而且可能会减慢我的代码速度。
英文:
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.
答案1
得分: 0
首先,你使用 InetAddress.getByName()
是多余的。Socket
有一个接受 String
输入的构造函数:
server = new Socket("127.0.0.1", 3333)
话虽如此,你应该为你的服务器注册一个静态域名,并设置其 DNS 记录指向你的服务器的 IP 地址。然后客户端可以使用该域名来连接服务器,而不是直接使用 IP 地址:
server = new Socket("mydomain", 3333)
如果你的服务器没有静态 IP,有很多免费和便宜的“动态 DNS”服务可用,允许你在 IP 地址更改时更新你的域名(通常使用自动化工具来简化检测和更新过程)。
如果服务器在路由器后面,许多路由器内置支持更新各种 DynDNS 服务。如果你的路由器支持此功能,你可以配置它使用你的 DynDNS 帐户信息,以便在其 WAN IP 更改时自动更新域名。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论