先引入命名空间:
using System.Collections; using System.Management; using System.Net; using System.Net.Sockets;
再编写代码如下:
public void scanPort() { string availPorts = ""; string usedPorts = ""; ManagementClass manage = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objCollection = manage.GetInstances(); ArrayList ips = new ArrayList(); foreach(ManagementObject obj in objCollection ) { if((bool)obj["IPEnabled"]) { Array ipArray = (Array)obj.Properties["IPAddress"].Value; ips.Add(ipArray.GetValue(0).ToString()); } } ips.Add("127.0.0.1"); ips.Add("0.0.0.0"); string ports = ""; Socket sock; IPEndPoint endPoint; for (int i = 2; i < 10000; i++) { for (int j = 0; j < ips.Count; j++) { try { if (i ==1031) { string aaa = ""; } sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); endPoint = new IPEndPoint(IPAddress.Parse(ips[j].ToString()), i); sock.Bind(endPoint); sock.Close(); availPorts += "|" + i; } catch(Exception ex) { usedPorts += "|" + i; break; } } } availPorts += "end"; usedPorts += "end"; }
结果中:
availPorts 为可用端口
usedPorts 为已使用端口