Check if a port is open

前端 未结 10 915
萌比男神i
萌比男神i 2020-12-08 10:37

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...<

10条回答
  •  一向
    一向 (楼主)
    2020-12-08 11:28

    A better solution where you can even specify a timeout:

    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;
        }
    }
    

    And, in 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
    

提交回复
热议问题