Site Overlay

Opening a Port and Testing TCP Connections with PowerShell

🔌 Opening a Port and Testing TCP Connections with PowerShell

This example demonstrates how to use PowerShell and the [System.Net.Sockets.TcpListener] class to create a simple TCP listener on port 80 and accept incoming connections.

⚙️ 1. Create and Start a TCP Listener

The following code creates a listener on port 80. It accepts incoming connections and prints the remote IP address of the client.

$listener = [System.Net.Sockets.TcpListener]::new(80)
$listener.Start()
Write-Host "Listening on port 80..."

while ($true) {
    $client = $listener.AcceptTcpClient()
    Write-Host "Connection received: $($client.Client.RemoteEndPoint)"
    # Connection remains open; does not close client; keeps listening.
}
            

📝 Explanation

  • $listener.Start(): Starts the listener and opens the port.
  • AcceptTcpClient(): Accepts an incoming connection and returns a client object.
  • Write-Host: Prints the IP and port of the remote client.
  • This is a basic example; it does not handle disconnections or client cleanup.
  • Ensure your firewall settings allow connections to the specified port (port 80).

🧪 2. Test the Connection

While the listener is running, you can test it using the following PowerShell command from the same machine or another machine on the same network:

Test-NetConnection -ComputerName localhost -Port 80
            

If the connection is successful, the listener will output a “Connection received” message.

💡 Summary

Opening a TCP port and testing incoming connections using PowerShell is straightforward. This script is a good starting point for understanding how TCP listeners work in PowerShell environments.

arif akyuz
Arif Akyüz

image
Başka cihazda görüntüle
Arif Akyüz Sistem Network Yöneticisi ve Siber Güvenlik Uzmanı
Arif Akyüz Sistem Network Yöneticisi ve Siber Güvenlik Uzmanı

Arif Akyüz
Bilgi Teknolojileri
Sistem Network Yöneticisi
ve Siber Güvenlik Uzmanı
[email protected]

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors