PS I want to connect to a friend using Java Sockets.

How do I connect to the Server (for example, ) located on the Internet and how does it connect to me if my ip is dynamic? How does he find me? How does he send me information? So, if he (server) can connect to me, then I, having a dynamic IP, can connect to a friend who also has a dynamic IP, knowing how the server does it. How he does it?

    1 answer 1

    @ Sergey Pestov , in a nutshell, the process usually proceeds a little differently than you imagine.

    The server has a static IP (for example, and it listens to the port (for example, 8888). You have a dynamic IP (say, now), but your router has a static one (say in the external network and in the internal (on another network interface (you are physically connected to it)).

    When your client says connect (), the socket receives the address (host: port) from the OS, for example Your OS writes it to the interface that is associated with the router (with the MAC address of the router ). The router forwards the request packet to the address, but changes the sender address to (it changes the port number (takes the “free” at the moment)) and remembers that the address on the internal interface corresponds to on the outside.

    Thus, the server will receive packets from and send its answers to this address. The router, having received the packet, finds the address of the recipient (you) in its NAT (Network Address Translation) table and forwards the packet to you, but already at the address (changes in the packet header)

    In general, it should be clear.

    • Thank you very much, Enlightened. Long understood your answer, but I understood. - Mencey
    • You can still ask: If only I have a static IP, can we communicate with a friend. If I understand the answer correctly, it turns out that only he can connect to me, and I will connect to him after he connects to me, knowing his address on the Router. So? - Mencey
    • Connect not to a static IP in your case will not work. The client connects, the connection is established, then the packet exchange goes "along the beaten track". You will not be able to connect (make connect () from the server side) again (at the address that you saw in the client's package) because client socket does not listen for connections. Those. A packet on a connection can and will reach via a router (if the previous connection has not yet been closed), but the client's OS will drop it. - avp
    • There was a question on the topic. What if on this friend's computer a tcp listener listens on the connection? He listens, for example, at, the router has its address (say, So, how can I connect to a "friend"? Here it is necessary (it seems so called) port forwarding, right? - Veikedo
    • one
      Yes. In the internet a lot of material on this topic. For example, here . - avp