Skip to content

Instantly share code, notes, and snippets.

@heinrich-ulbricht
Created April 18, 2019 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heinrich-ulbricht/e22ee038585ea33db1988d14f9b634f1 to your computer and use it in GitHub Desktop.
Save heinrich-ulbricht/e22ee038585ea33db1988d14f9b634f1 to your computer and use it in GitHub Desktop.
check if certain ports can be reached from your internal network or if they are blocked
# check if certain ports can be reached from your internal network or if they are blocked
# note: adapted from https://github.com/JustinGrote/Scripts/blob/master/Test-TCPPort.ps1
function Test-Port()
{
Param([string]$srv, $port = 135, $timeoutMs = 3000, [switch]$verbose)
$failed = $false
$ErrorActionPreference = "SilentlyContinue"
$tcpclient = New-Object System.Net.Sockets.TcpClient
$asyncRes = $tcpclient.BeginConnect($srv,$port,$null,$null)
# wait for the specified number of milliseconds
$wait = $asyncRes.AsyncWaitHandle.WaitOne($timeoutMs, $false)
# check for timeout
if(!$wait)
{
# close the connection and report timeout
$tcpclient.Close()
if ($verbose)
{
Write-Host "Connection Timeout"
}
$failed = $true
}
else
{
# close the connection and report the error if there is one
$Error.Clear()
$tcpclient.EndConnect($asyncRes) | Out-Null
if(!$?)
{
if($verbose)
{
Write-Host $Error[0]
}
$failed = $true
}
$tcpclient.Close()
}
return !$failed
}
$openPorts = @()
$mailPorts = 25,110,465,587,995
foreach ($port in $mailPorts)
{
$result = Test-Port portquiz.net -port $port -timeoutMs 500
if ($result)
{
Write-Host "Port is open: $port" -ForegroundColor Green
$openPorts += $port
} else {
Write-Host "Port is closed: $port" -ForegroundColor Red
}
}
Write-Host "Detected open ports:"
$openPorts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment