Search code examples
c#tcp

TcpListener TcpClient get IPAddress


I wish to get the IPAddress from

Server side

TcpListener ftp_listener = new TcpListener(IPAddress.Any, ftpport);
 newclient = listener.AcceptTcpClient();

how do I find newclient ipaddress please

client side

TcpClient ftpclient = new TcpClient();
 ftpclient.Connect(ipAddress, ftpport);

how do I find ftpclient ipaddress

Currently I am using

 TcpClient ftpclient = new TcpClient();

            //get IpAddress of Server
#pragma warning disable CS0618 // Type or member is obsolete
            IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
#pragma warning restore CS0618 // Type or member is obsolete

            ftpclient.Connect(ipAddress, ftpport);// "192.168.1.160", ftpport);

Is there a better way ...

Thanks


Solution

  • For both server and client, the approach for getting the remote endpoint (IP Address and Port) is the same.

    1. Get the client IP Address on the server:

      IPEndPoint remoteIpEndPoint = newclient.Client.RemoteEndPoint as IPEndPoint;
      Console.WriteLine("Client IP Address is: {0}", remoteIpEndPoint.Address);
      
    2. Get the server IP Address on the client:

          IPEndPoint remoteIpEndPoint = ftpclient.Client.RemoteEndPoint as IPEndPoint;
          Console.WriteLine("FTP Server IP Address is: {0}", remoteIpEndPoint.Address);