You are right, this is not trivial. The problem is NAT, or the transfer of network addresses . In fact, the IP address that you have on your local network is unique, but in the wider context of the public Internet, many people behind the same router will have the same public IP address. Thus, given the IP and some data, you cannot say exactly which person on the other end should receive it.
The most effective and simplest solution is for a third party to mediate the connection by inserting itself into the data stream. Instead of each person in the chat being a “client” and a “server” at the same time, there was only one server, and it was in a well-known public place; then everyone connects to it. The server then manages the messages and sends messages to people during the chat.
There are other solutions. For example, instead of using a well-known server, you can use the well-known port (s): all communications take place on that port (s). Then you do not need a server, but all endpoints must have this port open, which requires preliminary configuration.
source share