Created
May 1, 2021 18:13
-
-
Save karoltheguy/687c981569e5d1465b196b2ed7150d88 to your computer and use it in GitHub Desktop.
Listening to port in powershell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. [email protected] | |
| #> | |
| $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" | |
| } | |
| } | |
Author
Author
Event simpler one-liner:
([System.Net.Sockets.TcpListener]80).Start()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Possible to run something as simple as this as well (used port 80 as example):
$endpoint = new-object System.Net.IPEndPoint ([system.net.ipaddress]::any, 80)$listener = new-object System.Net.Sockets.TcpListener $endpoint$listener.start()Must enter $listener.Stop() to stop listening to the given port.