简体   繁体   English

改进从客户端获取服务器IP地址的方式

[英]Improving the way I get server's ip address from the client

MulticastSocket multicast_socket = new MulticastSocket(Dialogos.MULTICAST_PORTA);
InetAddress group = InetAddress.getByName(Dialogos.MULTICAST_IP_GRUPO);
multicast_socket.joinGroup(group);
byte[] msg = new byte[1024];
DatagramPacket packet = new DatagramPacket(msg, msg.length);
multicast_socket.receive(packet);

In the code above, the server is receiving a request from a client, via multicast. 在上面的代码中,服务器通过多播从客户端接收请求。 The server is now supposed to let the client know "where" it is. 服务器现在应该让客户端知道“它在哪里”。 This is just one method for the client to guess where to connect, it's not completely dependent on it. 这只是客户端猜测连接位置的一种方法,它并不完全依赖于它。

The server can be installed on many different environments though, so I don't know which interface/address will be used to communicate with the client. 服务器可以安装在许多不同的环境中,因此我不知道将使用哪个接口/地址与客户端通信。 Therefore, to tell the client where it is, I'm compiling all the available ip addresses in the server and sending them all back in a multicast, so that the client can try them out until one succeeds. 因此,为了告诉客户端它在哪里,我正在编译服务器中的所有可用IP地址并将它们全部发送回多播,以便客户端可以尝试它们直到成功。

My question: Is there a way to improve this mechanism? 我的问题:有没有办法改善这种机制? I wonder if, on the server app, I could get the local ip that received the multicast from the client, then I'd know which one to send back. 我想知道,在服务器应用程序上,我是否可以获得从客户端收到多播的本地IP,然后我知道要发回哪一个。 Can't find methods that do that though. 但是找不到那样做的方法。 Maybe some way to attempt a connection to the client just to know which local address it would pick to do so? 也许某种方式尝试连接到客户端只是为了知道它会选择哪个本地地址?

Just send unicast UDP packet back to the client, and the client will be able to extract the source IP address. 只需将单播UDP数据包发送回客户端,客户端就可以提取源IP地址。 That will ensure it's the address on the interface/route where client and server can talk to each other. 这将确保它是客户端和服务器可以相互通信的接口/路由上的地址。 You will need that packet to tell the listening port number somehow, of course. 当然,您将需要该数据包以某种方式告诉侦听端口号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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