检查如果一个端口是开放的 [英] Check if a port is open

查看:141
本文介绍了检查如果一个端口是开放的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法找到任何东西,告诉我,如果我在路由器端口是开放与否。 这甚至可能?

在code我现在并没有真正似乎工作...

 私人无效的SCANport()
    {
        字符串主机=localhost的;
        INT PORTNO = 9081;
        ip地址IPA =(ip地址)Dns.GetHostAddresses(主机名)[0];
        尝试
        {
            System.Net.Sockets.Socket袜子=
                新System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                                              System.Net.Sockets.SocketType.Stream,
                                              System.Net.Sockets.ProtocolType.Tcp);
            sock.Connect(IPA,PORTNO);
            如果(sock.Connected ==真)//端口正在使用中,连接成功
                的MessageBox.show(端口关闭);
            sock.Close();

        }
        赶上(System.Net.Sockets.SocketException前)
        {
            如果(ex.Error code == 10061)//端口没有用,无法建立连接
                的MessageBox.show(端口是开放的!);
            其他
                的MessageBox.show(ex.Message);
        }
    }
 

解决方案

试试这个:

 使用(的TcpClient的TcpClient =新的TcpClient())
{
    尝试 {
        tcpClient.Connect(127.0.0.1,9081);
        Console.WriteLine(打开端口);
    }赶上(例外){
        Console.WriteLine(端口封闭);
    }
}
 

您或许应该改变127.0.0.1到像192.168.0.1或任何你的路由器的IP地址。

I can't seem to find anything that tells me if a port in my router is open or not. Is this even possible?

The code I have right now doesn't really seem to work...

private void ScanPort()
    {
        string hostname = "localhost";
        int portno = 9081;
        IPAddress ipa = (IPAddress) Dns.GetHostAddresses(hostname)[0];
        try
        {
            System.Net.Sockets.Socket sock =
                new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                                              System.Net.Sockets.SocketType.Stream,
                                              System.Net.Sockets.ProtocolType.Tcp);
            sock.Connect(ipa, portno);
            if (sock.Connected == true) // Port is in use and connection is successful
                MessageBox.Show("Port is Closed");
            sock.Close();

        }
        catch (System.Net.Sockets.SocketException ex)
        {
            if (ex.ErrorCode == 10061) // Port is unused and could not establish connection 
                MessageBox.Show("Port is Open!");
            else
                MessageBox.Show(ex.Message);
        }
    }

解决方案

Try this:

using(TcpClient tcpClient = new TcpClient())
{
    try {
        tcpClient.Connect("127.0.0.1", 9081);
        Console.WriteLine("Port open");
    } catch (Exception) {
        Console.WriteLine("Port closed");
    }
}

You should probably change 127.0.0.1 to something like 192.168.0.1 or whatever your router's IP address is.

这篇关于检查如果一个端口是开放的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆