Last active
September 9, 2024 16:26
-
-
Save joegasper/c9eee2ca84c98881aa4ac341c648f398 to your computer and use it in GitHub Desktop.
TCP Listener in PowerShell
This file contains 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 Invoke-TcpListener { | |
<# | |
.SYNOPSIS | |
Starts a TCP listener on a specified port. | |
.DESCRIPTION | |
This function starts a TCP listener on a specified port, accepts incoming connections, | |
reads messages, and writes them to the terminal. It stops listening if the received | |
message is "exit". | |
.PARAMETER Port | |
The port number on which the TCP listener should listen for incoming connections. | |
.EXAMPLE | |
Invoke-TcpListener -Port 5140 | |
Starts a TCP listener on port 5140. | |
.NOTES | |
Author: @joegasper -and GPT-4o | |
Date: 2024-07-05 | |
#> | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory = $true)] | |
[int]$Port | |
) | |
begin { | |
# Initialize the TCP listener but do not start it | |
$listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Any, $Port) | |
Write-Verbose "TCP Listener initialized on port ${Port}." | |
} | |
process { | |
try { | |
# Start the TCP listener | |
$listener.Start() | |
Write-Verbose "TCP Listener started." | |
# Accept incoming connections and process them | |
while ($true) { | |
Write-Verbose "Waiting for incoming connections..." | |
# Accept an incoming connection | |
$client = $listener.AcceptTcpClient() | |
Write-Verbose "Connection accepted." | |
# Get the network stream from the client | |
$stream = $client.GetStream() | |
$reader = New-Object System.IO.StreamReader($stream, [System.Text.Encoding]::ASCII) | |
# Read the incoming message | |
$message = "" | |
while ($null -ne ($line = $reader.ReadLine())) { | |
$message += $line + "`n" | |
if ($line -eq "") { | |
break | |
} | |
Write-Verbose "Message accepted." | |
} | |
# Write the message to the terminal | |
Write-Host "`nReceived message:" | |
Write-Host ($message.Trim() + "`n") | |
# Close the client connection | |
$client.Close() | |
# Check if the message is "exit" | |
if ($message -match "^exit\r?\n?$") { | |
Write-Host "`nExit command received. Stopping TCP Listener..." | |
break | |
} | |
} | |
} | |
catch { | |
Write-Host "`nError: $_" | |
} | |
} | |
end { | |
# Stop the listener | |
$listener.Stop() | |
Write-Host "TCP Listener stopped." | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment