C#检查端口是否被占用

本文介绍了使用.net语言检查本地及指定IP地址下网络端口是否被占用的方法,包括检查特定端口(如4000)和所有端口。

--检查端口是否被占用
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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值