--检查端口是否被占用
Process p = new Process();
p.StartInfo = new ProcessStartInfo("netstat", "-a");
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string result = p.StandardOutput.ReadToEnd().ToLower();
if (result.IndexOf(Environment.MachineName.ToLower() + ":4000") >= 0)
MessageBox.Show("4000端口被占用");
else
{
MessageBox.Show("ok");
}
--检查所有的端口是否被占用
Process p = new Process();
p.StartInfo = new ProcessStartInfo("netstat", "-an");
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string result = p.StandardOutput.ReadToEnd().ToLower();//最后都转换成小写字母
string ip1 = "127.0.0.1";
string ip2 = "0.0.0.0";
System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
List<string> ipList = new List<string>();
ipList.Add(ip1);
ipList.Add(ip2);
for (int i = 0; i < addressList.Length; i++)
{
ipList.Add(addressList[i].ToString());
}
bool use = false;
for (int i = 0; i < ipList.Count; i++)
{
if (result.IndexOf("tcp " + ipList[i] + ":" + textBox1.Text) >= 0)
{
use = true;
break;
}
}
if (use)
{
MessageBox.Show("TCP" + textBox1.Text + "端口被占用","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else
{
MessageBox.Show("TCP" + textBox1.Text + "端口没有被占用", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
p.Close();
---正解,对于tcp是这样的,对于udp可以稍微修改一下:
if (result.IndexOf("tcp " + ipList[i] + ":" + textBox1.Text) >= 0)
修改为:
if (result.IndexOf("udp " + ipList[i] + ":" + chkPort) >= 0)///chkPort 就是你要检查的端口号,也就是#3楼 的 textBox1.Text
本文介绍了使用.net语言检查本地及指定IP地址下网络端口是否被占用的方法,包括检查特定端口(如4000)和所有端口。
3113

被折叠的 条评论
为什么被折叠?



