簡體   English   中英

TcpListener TcpClient 獲取 IP 地址

[英]TcpListener TcpClient get IPAddress

我希望得到來自ip地址

服務器端

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

我如何找到新的客戶IP 地址

客戶端

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

我如何找到ftpclient ipaddress

目前我正在使用

 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);

有沒有更好的辦法 ...

謝謝

對於服務器和客戶端,獲取遠程端點(IP 地址和端口)的方法是相同的。

  1. 獲取服務器上的客戶端 IP 地址:

     IPEndPoint remoteIpEndPoint = newclient.Client.RemoteEndPoint as IPEndPoint; Console.WriteLine("Client IP Address is: {0}", remoteIpEndPoint.Address);
  2. 在客戶端獲取服務器 IP 地址:

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

首先你的服務器代碼是錯誤的,在啟動服務器之前你不能接受客戶端所以代碼需要像這樣

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

// getting the client ip 2 ways :
var clientIpLAN = newclient.Client.LocalEndPoint; // locally this return "127.0.0.1:[YourServerFTPPort]"
var clientIpWAN = newclient.Client.RemoteEndPoint; // locally this return "127.0.0.1:[totally random port]"

為客戶端獲取魔法無法找到的服務器IP。 您需要知道要連接的位置。 有很多方法,但都需要 1 個您知道始終可用的靜態位置。 例如,Web 服務可以為您提供可立即連接的有效 IP 列表(或單個)。 您可能有一個 Web 數據庫,其中包含您可以連接的 IP。 如果您總是讓服務器和客戶端在同一台計算機上運行,​​那么localhost127.0.0.1幾乎總是可以工作,因為沒有主機文件惡作劇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM