Java - How to retrieve server IP with known port on Local Area Network [closed]

StackOverflow https://stackoverflow.com/questions/18538050

  •  26-06-2022
  •  | 
  •  

Вопрос

I can't seem to find a way to retrieve the server IP with the known port number. I have tried to go about by testing every single IP, but that was too slow. I read online something about Datagrams used to broadcast information but I can't seem to understand how to use them. all in all I am trying to get a chat client to connect to a server with a dynamic IP. But the problem is when the IP changes the client can't connect so I am trying to figure out a way to get a broadcast on a port and any client using that port can obtain the IP from the broadcast? ... Any thoughts???

UPDATE: In advance ... I already know how to retrieve the server's IP. I just need to be able to broadcast that IP on a socket with no client's connected therefor the clients can retrieve the IP from the broadcast and then connect to the server

Это было полезно?

Решение

Here are the steps: Create a UDP socket, set SO_BROADCAST option on that socket, put the server's IP address in a message and then broadcast the message by calling sendto() with 255.255.255.255 as destination. Of course, you would also need a common port number on which all the clients needs to bind so they can receive the broadcast message.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top