Skip to content

Instantly share code, notes, and snippets.

@tberta
Last active June 27, 2023 15:43
Show Gist options
  • Select an option

  • Save tberta/97ae4ebc109bcba369700ccbf2979140 to your computer and use it in GitHub Desktop.

Select an option

Save tberta/97ae4ebc109bcba369700ccbf2979140 to your computer and use it in GitHub Desktop.
Powershell functions to Listen on Custom TCP Port and Test Connection with speed
Function Test-TCP {
<#
.SYNOPSIS
Test TCP Port with a low and configurable timeout
.NOTES
Not my own work. Copyright to the author.
#>
Param($address, $port, $timeout = 250)
$socket = New-Object System.Net.Sockets.TcpClient
try {
$result = $socket.BeginConnect($address, $port, $NULL, $NULL)
if (!$result.AsyncWaitHandle.WaitOne($timeout, $False)) {
#throw [System.Exception]::new('Connection Timeout')
$ret = $false
}
else {
$socket.EndConnect($result) | Out-Null
$ret = $socket.Connected
}
}
Catch {
$ret = $false
}
Finally {
$socket.Close()
}
return $ret
}
New-Alias tt Test-Tcp
function Listen-Port ($port = 80) {
<#
.DESCRIPTION
Temporarily listen on a given port for connections dumps connections to the screen - useful for troubleshooting
firewall rules.
.PARAMETER Port
The TCP port that the listener should attach to
.EXAMPLE
PS C:\> listen-port 443
Listening on port 443, press CTRL+C to cancel
DateTime AddressFamily Address Port
-------- ------------- ------- ----
3/1/2016 4:36:43 AM InterNetwork 192.168.20.179 62286
Listener Closed Safely
.INFO
Created by Shane Wright. Neossian@gmail.com
#>
$endpoint = New-Object System.Net.IPEndPoint ([system.net.ipaddress]::any, $port)
$listener = New-Object System.Net.Sockets.TcpListener $endpoint
$listener.server.ReceiveTimeout = 3000
$listener.start()
try {
Write-Host "Listening on port $port, press CTRL+C to cancel"
While ($true) {
if (!$listener.Pending()) {
Start-Sleep -Seconds 1;
continue;
}
$client = $listener.AcceptTcpClient()
$client.client.RemoteEndPoint | Add-Member -NotePropertyName DateTime -NotePropertyValue (Get-Date) -PassThru
$client.close()
}
}
catch {
Write-Error $_
}
finally {
$listener.stop()
Write-Host "Listener Closed Safely"
}
}
Listen-Port 443
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment