6

As a beginner in C# networking, I wrote a simple Client-Server application. I'm connecting to my local IPAddress and port 8080 where the server is listening.

On Client Side:

        IPAddress remoteaddr = IPAddress.Parse("127.0.0.1");
        int port = 8880;
        TcpClient tcpclient = new TcpClient();
        tcpclient.Connect(remoteaddr, port);
        NetworkStream networkstream = tcpclient.GetStream();

        IPEndPoint RemAddr = (IPEndPoint)tcpclient.Client.RemoteEndPoint;
        IPEndPoint LocAddr = (IPEndPoint)tcpclient.Client.LocalEndPoint;

        if (RemAddr != null)
        {
            // Using the RemoteEndPoint property.
            Console.WriteLine("I am connected to " + RemAddr.Address + "on port number " + RemAddr.Port);
        }

        if (LocAddr != null)
        {
            // Using the LocalEndPoint property.
            Console.WriteLine("My local IpAddress is :" + LocAddr.Address + "I am connected on port number " + LocAddr.Port);
        }

the output is:

I am connected to 127.0.0.1 on port number 8880
My local IpAddress is :127.0.0.1 I am connected on port number 46715

So What's the difference between RemoteEndPoint and LocalEndPoint? What is the use of LocalEndPoint Port (46715 in my example) and where does it came from? Thanks.

user3723486
  • 189
  • 1
  • 3
  • 12
  • 1
    A TCP socket is a two sided connection - the local endpoint is your client's side, the remote endpoint is the server's side - that the server happens to be on the same hardware as the client doesn't mean you don't still have a pipe with two ends. The local port number is decided by the TCP stack at the time the connection is made. – Preston Guillot Jan 01 '16 at 17:39
  • 2
    The answer to [this question](https://stackoverflow.com/questions/13190176/how-does-port-number-really-work-in-tcp) may help you, your question is less specific to the .Net `TcpClient` class and more generally about how TCP/IP works. – Preston Guillot Jan 01 '16 at 17:42

1 Answers1

2

Remote End point will show you which client(ip) is connected to you're local end point (that is more likely to be the server ip 127.0.0.1)