如何将十六进制字符串传递给TCP连接并读取结果

时间:2016-07-13 13:51:47

标签: powershell tcp hex powershell-v2.0

我有以下脚本(感谢@SavindraSingh的链接)。

我正在尝试将$message传递给$remotehost $port并捕获回复。

$port=12345
$remoteHost = "1.2.3.4"
$message="\x40\x00\x23\x01\x00\x00\x00\x40"

$socket = new-object System.Net.Sockets.TcpClient($remoteHost, $port)

$data = [System.Text.Encoding]::ASCII.GetBytes($message)

$stream = $socket.GetStream()
$stream.Write($data, 0, $data.Length)

问题在于ASCII.GetBytes会将每个角色转换为其个别'字节' (如预期的那样)。 但是,如果我只是$data=$message,我会收到以下错误:

Cannot convert argument "0", with value: "\x40\x00\x23\x01\x00\x00\x00\x40", for "Write" to type "System.Byte[]"
: "Cannot convert value "\x40\x00\x23\x01\x00\x00\x00\x40" to type "System.Byte[]". Error: "Cannot convert value
"\x40\x00\x23\x01\x00\x00\x00\" to type "System.Byte". Error: "Input string was not in a correct format."""
At line:13 char:14
+ $stream.Write <<<< ($data, 0, $data.Length)
+ CategoryInfo          : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

如何传递$message(一串十六进制值)。

我如何看待回复(write-host $stream只是说System.Net.Sockets.NetworkStream)。

---更新2016-07-14 ---

根据文档以及我在其他地方收集过的文章,我添加了以下内容以尝试阅读回复:

$reader = New-Object System.IO.StreamReader($stream)

$buffer = new-object System.Byte[] 1024
$encoding = new-object System.Text.AsciiEncoding

$rawresponse = ""

$response1 = $reader.Read($buffer, 0, 1024)
$response2 = $encoding.GetString($buffer, 0, $rawresponse)

write-host $response1
write-host $response2

但是从此$response1始终返回0,20或21而$response2不返回任何内容。 我期待一个类似于#@3e1###f9的文本字符串,这是我的应用程序应该返回的内容。

我在某个地方误解了什么吗?

0 个答案:

没有答案