检查端口是否打开

Yuk*_*uya 23 .net c# winforms

我似乎无法找到任何告诉我路由器中的端口是否打开的东西.这甚至可能吗?

我现在的代码似乎并没有真正起作用......

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Cli*_*ard 38

试试这个:

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

您应该将127.0.0.1更改为192.168.0.1或路由器的IP地址.


ymp*_*tor 22

一个更好的解决方案,您甚至可以指定超时:

using System;
using System.Net.Sockets;

// ...

bool IsPortOpen(string host, int port, TimeSpan timeout)
{
    try
    {
        using(var client = new TcpClient())
        {
            var result = client.BeginConnect(host, port, null, null);
            var success = result.AsyncWaitHandle.WaitOne(timeout);
            client.EndConnect(result);
            return success;
        }
    }
    catch
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

而且,在F#中:

open System
open System.Net.Sockets

let isPortOpen (host: string) (port: int) (timeout: TimeSpan): bool =
    try
        use client = new TcpClient()
        let result = client.BeginConnect(host, port, null, null)
        let success = result.AsyncWaitHandle.WaitOne timeout
        client.EndConnect result
        success
    with
    | _ -> false

let available = isPortOpen "stackoverflow.com" 80 (TimeSpan.FromSeconds 10.)
printf "Is stackoverflow available? %b" available
Run Code Online (Sandbox Code Playgroud)

  • `client.EndConnect` 将等待 20 秒(默认超时),因此这不起作用 (2认同)