c# 端口

来源:互联网 发布:雕刻机的编程软件 编辑:程序博客网 时间:2024/05/28 05:18

这几天  老总让写一个检测本地端口是否启用的程序,网上找了好多的例子  都不能达到理想的效果,最后勉强能实现效果

在次  总结了一下  有关端口的各种问题(这里有用别人总结好的东西)

---能否拼通端口,即 端口是否已经打开  这个效果很明显 

 private static bool cmdTelnet(string strIP, int strNum)
        {

//参数介绍  第一个是IP  第二个是端口号
            bool strTelnet;

            try
            {
                IPAddress ip = IPAddress.Parse(strIP);
                IPEndPoint point = new IPEndPoint(ip, strNum);
                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock.Connect(point);
                //strTelnet = string.Format("连接端口{0} 成功!", point);
                strTelnet = true;
            }
            catch (SocketException e)
            {
                if (e.ErrorCode != 10061)
                {
                    MessageBox.Show(e.Message.ToString(), "提示", MessageBoxButtons.OK);
                }
               // strTelnet = string.Format("连接{0} 失败", strIP + ":" + strNum);
                strTelnet = false;
            }
            return strTelnet;
        }

 

--检查端口是否被占用  --这个占用可以用
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");
}

-----------第三种不太理解,也没有达到预期的效果,拿出来大家研究一下吧

  public static bool GetPortMessage(string ip,int port)
        {
            bool tcpListen = false;
            bool udpListen = false;
            //设定端口状态标识位
            System.Net.IPAddress myIpAddress = IPAddress.Parse(ip);
            System.Net.IPEndPoint myIpEndPoint = new IPEndPoint(myIpAddress, port);
            try
            {
                TcpClient tcpClient=new TcpClient();
               
                tcpClient.Connect(myIpEndPoint);                            
                //对远程计算机的指定端口提出TCP连接请求
                tcpListen=true;
            }
            catch
            {             
            }
            try
            {
                UdpClient udpClient=new UdpClient();
                udpClient.Connect(myIpEndPoint);
                //对远程计算机的指定端口提出UDP连接请求
                udpListen=true;
            }
            catch
            {
             
            }
            if(tcpListen==false&&udpListen==false)
            {
                //MessageBox.Show("8000端口关闭!","提示");
                return false;
            }
            else
            {
                //MessageBox.Show("8000端口打开!","提示");
                return true;
            }
        }

原创粉丝点击