Socket Client over PowerShell
·2 mins
Table of Contents
In this article let’s use PowerShell to create a socket client and do a simple call to a webserver.
There are multiple ways to create sockets using PowerShell. For this article let’s take use
TcpClientobject for it’s simplicity.
Table of Contents #
Set up the Client Socket #
Let’s start by creating the client object. TcpClient it’s a very easy way to handle TCP connections as a client.
We’re going to use the web server https://httpbin.org/ to connect our client.
# Creates the TCP Client
$client = New-Object System.Net.Sockets.TcpClient
# Connect to the server
$client.Connect("eu.httpbin.org", 80)
Sending the Request #
Since we’re calling a Web Server HTTP 1.1. We must send the appropriate request as a HTTP 1.1 client.
# Data mimicking a web client
$payload = "GET /get HTTP/1.1
Host: eu.httpbin.org
Accept: */*
"
$bytesPayload = [System.Text.Encoding]::ASCII.GetBytes($payload)
$stream.Write($bytesPayload, 0, $bytesPayload.Length)
Reading the Response #
Once the request is sent we must immediately start reading the response.
# Receive data from the server
$bufferResponse = New-Object byte[] 4096 #enough to read our response 4mb
$bytesRead = $stream.Read($bufferResponse, 0, $bufferResponse.Length)
$response = [System.Text.Encoding]::ASCII.GetString($bytesRead, 0, $bytesRead)
# Output the Response
Write-Host $response
Finally! Close the connection #
Don’t forget to close the connection. 🚀
# Close the connection
$stream.Close()
$client.Close()
Complete Code #
# Create a TCP client object
$client = New-Object System.Net.Sockets.TcpClient
# Connect to the server
$client.Connect("eu.httpbin.org", 80)
# Get the network stream for reading and writing
$stream = $client.GetStream()
# Send data to the server
$data = "GET /get HTTP/1.1
Host: eu.httpbin.org
Accept: */*
"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($data)
$stream.Write($bytes, 0, $bytes.Length)
# Receive data from the server
$buffer = New-Object byte[] 1024
$bytesRead = $stream.Read($buffer, 0, $buffer.Length)
$response = [System.Text.Encoding]::ASCII.GetString($buffer, 0, $bytesRead)
# Display the response
Write-Host $response
# Close the connection
$stream.Close()
$client.Close()