c# 如何获取TcpClient占用的网络端口

来源:百度知道 编辑:UC知道 时间:2024/05/16 06:12:52
如题
1楼太麻烦了 Native API编程也看不懂
2楼你自己都把ip端口打出来再获取有个鸟用

我说的是客户端获取自己的端口,好像随机生成的

首先在CMD下输入netstat -ano可以达到你想到要结果。

C#不直接支持获取被打开/连接的网络端口功能,你有两种方法可以实现,
1. 使用Process.Start("cmd", "netstat -ano"),然后把结果重定向输出,自己分析一下输出流就可以了。
2. 使用Native API编程,可以参考以下信息。
http://msdn.microsoft.com/en-us/library/aa365928(VS.85).aspx
代码是C语言的,你可以稍加修改,改成C#的。

用下面方法获取远程IP和端口
TcpClient tc = new TcpClient();
tc.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.100"), 4567));
IPEndPoint remoteIEP = (IPEndPoint)tc.Client.RemoteEndPoint;
MessageBox.Show(remoteIEP.Address.ToString());//远程IP
MessageBox.Show(remoteIEP.Port.ToString());//远程端口

获得自己的端口也差不多
IPAddress[] ip = Dns.GetHostAddresses();
TcpClient tc = new TcpClient(new IPEndPoint(ip[0],4567));
tc.Client.Listen(1);
IPEndPoint localIEP = (IPEndPoint)tc.Client.LocalEndPoint;
MessageBox.Show(localIEP.Address.ToStr