Skip to content

Instantly share code, notes, and snippets.

@DexterPOSH
Created March 14, 2016 06:15
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 DexterPOSH/cec7df741a8682668839 to your computer and use it in GitHub Desktop.
Save DexterPOSH/cec7df741a8682668839 to your computer and use it in GitHub Desktop.
Test-PortReachableUsingSourceIP
Function Test-PortReachableUsingSourceIP
{
[CmdletBinding()]
[Alias()]
[OutputType([int])]
Param
(
# Specify the remote destination IPAddress.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string[]]$Destination,
# Specify the remote destination port to check.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateRange(1,65535)]
[int]$DestinationPort,
# Specify the source IPAddress to use.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ipaddress]$SourceIP
)
Process
{
Write-Verbose -Verbose -Message "[Test-PortReachableUsingSourceIP] Invoked . Destination -> $Destination ; DestinationPort -> $DestinationPort ; SourceIP -> $SourceIP"
TRY {
Write-Verbose -Verbose -Message "[Test-PortReachableUsingSourceIP] Creating list of locally used ports."
$UsedLocalPorts = ([System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()).GetActiveTcpListeners() |
where -FilterScript {$PSitem.AddressFamily -eq 'Internetwork'} |
Select -ExpandProperty Port
# select a non-used port
do {
$localport = $(Get-Random -Minimum 49152 -Maximum 65535 )
} until ( $UsedLocalPorts -notcontains $localport)
Write-Verbose -Verbose -Message "[Test-PortReachableUsingSourceIP] Found an unused local port -> $LocalPort"
Write-Verbose -Verbose -Message "[Test-PortReachableUsingSourceIP] Creating a Local EndPoint"
$LocalIPEndPoint = New-Object -TypeName System.Net.IPEndPoint -ArgumentList $SourceIP,$localport
Write-Verbose -Verbose -Message "[Test-PortReachableUsingSourceIP] Local Endpoint created $LocalIPEndpoint"
}
CATCH {
$PSCmdlet.ThrowTerminatingError($PSItem)
}
TRY {
$TCPClient = New-Object -TypeName System.Net.Sockets.TcpClient -ArgumentList $LocalIPEndPoint
Write-Verbose -Verbose -Message "[Test-PortReachableUsingSourceIP] Created a TCPClient"
$TCPClient.Connect($Destination,$DestinationPort)
if ($TCPClient.Connected) {
# Port is Open
Write-Verbose -Verbose -Message "[Test-PortReachableUsingSourceIP] TCPClient successfully connected to Destination -> $Destination on Port -> $DestinationPort"
Write-Output -InputObject $true
}
else {
# Port is not open
Write-Verbose -Verbose -Message "[Test-PortReachableUsingSourceIP] TCPClient unable to connect to Destination -> $Destination on Port -> $DestinationPort"
Write-Output -InputObject $false
}
}
CATCH {
# DO something here
$PSCmdlet.ThrowTerminatingError($PSItem)
}
} #end Process
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment