Check if a port is open

前端 未结 10 911
萌比男神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:23

    If you're connecting to the loopback adapter — localhost or 127.0.0.1 (there's no place like 127.0.0.1!), you're unlikely to ever go out to the router. The OS is smart enough to recognize that it's a special address. Dunno if that holds true as well if you actually specify your machine's "real" IP address.

    See also this question: What is the purpose of the Microsoft Loopback Adapter?

    Also note that running traceroute localhost (tracert localhost in Windows) shows that the only network node involved is your own machine. The router is never involved.

    0 讨论(0)
  • 2020-12-08 11:23

    If it is Router the simplest way to check it through online services like

    • Port Checker
    • Port Forwarding Test

    You can also try using telenet to chek wether port is accessible or not

    telenet [ip-address] [port] 
    
    0 讨论(0)
  • 2020-12-08 11:27

    A port forward on the router cannot be tested from inside the LAN, you need to connect from the WAN (internet) side to see if a port forward is working or not.

    Several internet sites offer services to check if a port is open:

    What's My IP Port Scanner

    GRC | ShieldsUP!

    If you want to check with your own code, then you need to make sure the TCP/IP connection is rerouted via an external proxy or setup a tunnel. This has nothing to do with your code, it's basic networking 101.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题