Tuesday, October 15, 2019

Powershell listening on a port

$socket = new-object System.Net.Sockets.TcpListener('0.0.0.0', 1080);
if($socket -eq $null){
exit 1;
}
$socket.start();
$client = $socket.AcceptTcpClient();
$stream = $client.GetStream();
$buffer = new-object System.Byte[] 2048;

try
{
    do
    {
    $read = $null;
    while($stream.DataAvailable -or $read -eq $null) {
    $read = $stream.Read($buffer, 0, 2048);
    if ($read -gt 0) {
                    $data = [System.Text.Encoding]::ASCII.GetString($buffer).Trim(0x00).TrimEnd()
                    $buffer.Clear()
                    if($data -ne $null -and $data .Length -gt 0){
                        Write-Output ("RECEIVED : [{0}]" -f $data)
                        $sendBack = new-object System.Byte[] 2048;
                        $sendBack = [System.Text.Encoding]::UTF8.GetBytes($data)
                        $stream.Write($sendBack, 0, $results.Length)
                        $sendBack.Clear()
                        Write-Output ("SENT BACK: [{0}]" -f $data)
                            }
    }
    }
    } While ($read -gt 0);
}
finally
{
    $fileStream.Close();
    $socket.Stop();
    $client.close();
    $stream.Dispose();
}

No comments:

Post a Comment