Thursday, January 23, 2025

[Powershell] A script to listen a given TCP port

 # Manually execute "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process"

# Name this file as Listen-TCP.ps1

param (
    [int]$Port = 8080  # Default port is 8080, you can specify another port when running the script
)

$gsock = {
	# Create a TCP listener on the specified port
	$listener = [System.Net.Sockets.TcpListener]$Port
	$listener.Start()

	Write-Host "Listening on port $Port..."

	try {
		while ($true) {
			# Accept a client connection
			$client = $listener.AcceptTcpClient()
			Write-Host "Client connected!"

			# Get the network stream for reading data
			$stream = $client.GetStream()

			# Set up a reader to read from the stream
			$reader = New-Object System.IO.StreamReader($stream)

			# Read the data from the stream
			while ($reader.Peek()) {
				$data = $reader.ReadLine()
				Write-Host "Received: $data"
			}

			# Close the client connection
			$reader.Close()
			$client.Close()
		}
	}
	catch {
		Write-Host "Error: $_"
	}
	finally {
		# Stop the listener when done
		$listener.Stop()
		Write-Host "Listener stopped."
		.$gsock
	}
}

&$gsock
# .\Listen-TCP.ps1 -Port 9090

No comments:

Post a Comment