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); } }
You can test whether the port is open by attempting to open an HTTPS connection to the computer using its domain name or IP address. To do this, you type https://www.example.com in your web browser's URL bar, using the actual domain name of the server, or https://192.0.2.1, using the server's actual numeric IP address.
Type netstat -ab and press Enter. You'll see a long list of results, depending on what's currently connecting to the network. You'll see a list of running processes. The open port numbers will be after the last colon on the local IP address (the one on the left).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With