问题
I have the following script (thanks to @SavindraSingh for the link).
I am trying to pass the $message
below to the $remotehost $port
and capture the response.
$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)
The problem is that the ASCII.GetBytes
converts each character to it's individual 'bytes' (as expected).
However, if I simply do $data=$message
I get the following error:
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
How can I pass across my $message
(a string of hex values).
And how would I see the response (write-host $stream
just says System.Net.Sockets.NetworkStream
).
--- UPDATE 2016-07-14 ---
Based on the documentation, and pieces I've gleaned elsewhere, I've added the following to try and Read the response:
$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
But from this $response1
always returns 0, 20 , or 21 And $response2
returns nothing.
I was expecting a text string similar to #@3e1###f9
which is what my application should be returning.
Have I misunderstood something somewhere?
来源:https://stackoverflow.com/questions/38353658/how-to-pass-a-hex-string-to-a-tcp-connection-and-read-the-result