Skip to content

Instantly share code, notes, and snippets.

@gregjhogan
Last active January 16, 2017 22:19
Show Gist options
  • Select an option

  • Save gregjhogan/c76217605b0ce274234c8fe77cc2debe to your computer and use it in GitHub Desktop.

Select an option

Save gregjhogan/c76217605b0ce274234c8fe77cc2debe to your computer and use it in GitHub Desktop.
Listen on a tcp port
function Trace-Port([string]$IPAddress="127.0.0.1", [int]$Port=80, [switch]$Echo=$false){
$listener = new-object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Parse($IPAddress), $port)
$listener.start()
[byte[]]$bytes = 0..255|%{0}
write-host "Waiting for a connection on port $port..."
$client = $listener.AcceptTcpClient()
write-host "Connected from $($client.Client.RemoteEndPoint)"
$stream = $client.GetStream()
while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0)
{
$bytes[0..($i-1)]|%{$_}
if ($Echo){$stream.Write($bytes,0,$i)}
}
$client.Close()
$listener.Stop()
write-host "Connection closed."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment