Send Hex Decimal over TCP / IP - vb.net

Im Developing a client to send information to a specific server. And the server accept only a spesific data from the client. The Data is "163130303030323030fc". I have converted it into Ascii as
"SYN10000200ü"
it works except "SYN". The "SYN" has to be converted to "16" to make it happen. But when I use the code Encoding.Default.GetBytes("<SYN>10000200ü") the result receive as
3c53594e3e3130303030323030fc
The code Im Using Is as follows ,
Dim tcpClient As New System.Net.Sockets.TcpClient()
Try
tcpClient.Connect("192.168.18.6", 60010)
Dim networkStream As NetworkStream = tcpClient.GetStream()
If networkStream.CanWrite And networkStream.CanRead Then
Dim sendBytes As Byte() = Encoding.Default.GetBytes("<SYN>10000200ü")
networkStream.Write(sendBytes, 0, sendBytes.Length)
Do
Loop Until networkStream.DataAvailable
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
Dim returndata As String = Encoding.ASCII.GetString(bytes)
TextBox1.Text &= returndata
tcpClient.Close()
Else
If Not networkStream.CanRead Then
tcpClient.Close()
Else
If Not networkStream.CanWrite Then
tcpClient.Close()
End If
End If
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
It ok if there's a way to send the data in hex without encording to ascii
Your kind Consideration is highly appreciated !

If you need the String to be sent as text, and not hex, the SYN-character would convert to char 22. Refer to the DEC/Decimal column in an ASCII table.
Try doing this:
Encoding.ASCII.GetBytes(ChrW(22) & "10000200ü")
Else if it must be sent as HEX, just send the hex string as it is:
Encoding.Default.GetBytes("163130303030323030fc")

Related

length of character in redis value

hay, I'm new in Redis. I want to create my own redis-cli with vb.net. I found a reference like this
Imports System.Net.Sockets
Imports System.Text
Module Module1
Sub Main()
Dim stream As NetworkStream
Dim client As TcpClient
Dim bytes() As Byte
Dim result As String
Try
client = New TcpClient()
client.Connect("127.0.0.1", 6379)
stream = client.GetStream()
bytes = Encoding.UTF8.GetBytes("keys *" & vbCrLf)
stream.Write(bytes, 0, bytes.Length)
stream.Flush()
ReDim bytes(client.ReceiveBufferSize)
stream.Read(bytes, 0, bytes.Length)
result = Encoding.UTF8.GetString(bytes)
result = Left(result, InStrRev(result, vbCrLf))
Console.WriteLine("Result:" + result)
Catch ex As Exception
Console.WriteLine("Error:" + ex.ToString())
End Try
End Sub
End Module
actually it works. but why the result always gives me a length of character? where I can delete or remove it? the result is like this:
yeah, because I just have 1 key

vb.net weight scale tcpip not getting data

i am new to vb.net 2008 to get data from weigh scale using tcpclient(). below mentioned code is able to connect with machine but not getting the data. But hyperterminal is able to get data.
I searched most of the post but may coding exist only for serial port connection.
Output MsgBox :
Received: {0}
Imports System.Net.Sockets
Public Sub Connect(ByVal server As [String], ByVal _Ports As Int32, ByVal message As [String])
Try
' Create a TcpClient.
' Note, for this client to work you need to have a TcpServer
' connected to the same address as specified by the server, port
' combination.
Dim port As Int32 = _Ports
Dim client As New TcpClient()
'Dim client As New TcpClient(server, port)
client.Connect(server, port)
If client.Client.Connected Then TextBox3.Text = "Connected"
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
Dim stream As NetworkStream = client.GetStream()
Dim Buffer(client.ReceiveBufferSize) As Byte
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
'Console.WriteLine("Sent: {0}", message)
MsgBox("Sent: {0} " & message)
' Receive the TcpServer.response.
' Buffer to store the response bytes.
data = New [Byte](2047) {}
'MsgBox("Response Byte - " & data.Length)
' String to store the response ASCII representation.
Dim responseData As [String] = [String].Empty
' Read the first batch of the TcpServer response bytes.
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
'Console.WriteLine("Received: {0}", responseData)
MsgBox("Received: {0} " & responseData)
' Close everything.
stream.Close()
client.Close()
Catch e As ArgumentNullException
'Console.WriteLine("ArgumentNullException: {0}", e)
MsgBox("ArgumentNullException: {0}" & e.Message)
Catch e As SocketException
'Console.WriteLine("SocketException: {0}", e)
MsgBox("SocketException: {0}" & e.Message)
End Try
MsgBox("Got to this point in code")
'Console.WriteLine(ControlChars.Cr + " Press Enter to continue...")
'Console.Read()
End Sub
This:
MsgBox("Received: {0} " & responseData)
...does not automatically replace {0} with the value of responseData.
The {0} placeholder is used with the String.Format() function. Change your code to this, in all applicable places, and check the result:
' Let's also get rid of the legacy VB6 MsgBox() function:
MessageBox.Show(String.Format("Received: {0} ", responseData))
Also, what's with the square brackets around some data types (i.e. [String])? They aren't needed.

Using vb.net ReadAllBytes

I used vb .NET function ReadAllBytes to read a file and send it over a socket. When received, I used WriteAllBytes. The problem is they are not same size! The original is 16kb, but the received data is 24kb. My code is below. What am I doing wrong?
Dim bteRead() As Byte
Try
bteRead = IO.File.ReadAllBytes(filepath)
Catch ex As System.IO.IOException
End Try
Return bteRead
then i convert bytes to string and send it , and when received i convert it back from string to bytes and do the WriteAllBytes
Dim str As String = a(1)
Dim encod As New System.Text.UTF8Encoding
Dim byteData() As Byte = encod.GetBytes(str)
IO.File.WriteAllBytes("c:\lol.db", byteData)
Solution for me was to change:
Dim encod As New System.Text.UTF8Encoding
Dim byteData() As Byte = encod.GetBytes(str)
To
Dim byteData() As Byte = System.Text.Encoding.Default.GetBytes(str)

get byte or image from Crypto Service Provider

I used This Code To Encrypt and Decrypt Data In my application
but the code use File Stream to do all work This is the code :
Dim bytKey As Byte()
Dim bytIV As Byte()
bytKey = CreateKey("mrbrashad1999")
bytIV = CreateIV("mrbrashad1999")
Try 'In case of errors.
'Setup file streams to handle input and output.
fsInput = New System.IO.FileStream(strInputFile, FileMode.Open, _
FileAccess.Read)
fsOutput = New System.IO.FileStream(strOutputFile, FileMode.OpenOrCreate, _
FileAccess.Write)
fsOutput.SetLength(0) 'make sure fsOutput is empty
'Declare variables for encrypt/decrypt process.
Dim bytBuffer(4096) As Byte 'holds a block of bytes for processing
Dim lngBytesProcessed As Long = 0 'running count of bytes processed
Dim lngFileLength As Long = fsInput.Length 'the input file's length
Dim intBytesInCurrentBlock As Integer 'current bytes being processed
Dim csCryptoStream As CryptoStream
'Declare your CryptoServiceProvider.
Dim cspRijndael As New System.Security.Cryptography.RijndaelManaged
'Setup Progress Bar
'pbStatus.Value = 0
'pbStatus.Maximum = 100
'Determine if ecryption or decryption and setup CryptoStream.
Select Case Direction
Case CryptoAction.ActionEncrypt
csCryptoStream = New CryptoStream(fsOutput, cspRijndael.CreateEncryptor(bytKey, bytIV), CryptoStreamMode.Write)
Case CryptoAction.ActionDecrypt
csCryptoStream = New CryptoStream(fsOutput, cspRijndael.CreateDecryptor(bytKey, bytIV), CryptoStreamMode.Write)
End Select
'Use While to loop until all of the file is processed.
While lngBytesProcessed < lngFileLength
'Read file with the input filestream.
intBytesInCurrentBlock = fsInput.Read(bytBuffer, 0, 4096)
'Write output file with the cryptostream.
csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock)
'Update lngBytesProcessed
lngBytesProcessed = lngBytesProcessed + CLng(intBytesInCurrentBlock)
'Update Progress Bar
'pbStatus.Value = CInt((lngBytesProcessed / lngFileLength) * 100)
End While
'Close FileStreams and CryptoStream.
csCryptoStream.Close()
fsInput.Close()
fsOutput.Close()
'Catch file not found error.
Catch When Err.Number = 53 'if file not found
MsgBox("Please check to make sure the path and filename" + _
"are correct and if the file exists.", _
MsgBoxStyle.Exclamation, "Invalid Path or Filename")
'Catch all other errors. And delete partial files.
Catch
fsInput.Close()
fsOutput.Close()
End Try
what i should do to get byte() or image From encrypted data in my file system direct to my application variable .
A CryptoStream simply sits on top of another Stream. When you Write to the CryptoStream, it takes the Byte array that you pass in, encrypts it and populates another array with the result, then it will Write that to the underlying Stream. Likewise, when you call Read it will call Read on the underlying Stream, decrypt it and then pass you the result. In your case you are using a FileStream but it can be any type of Stream at all, e.g. NetworkStream or GZipStream. If you want a temporary place to store binary data within your app then you can use a MemoryStream. The code to use the Stream is the same regardless of its type.

VB.NET convert UCS-2 bytes to ASCII

Ok so i am working on this program which sends a packet to a minecraft server and in return it gives me information about the server;(message of the day, players online, max players)
The problem is the response is in UCS-2
So when i send the packet to the server and get the response in bytes. How do i convert it to ascii so i can work with it?
Here is my code so far
Dim client As New System.Net.Sockets.TcpClient()
client .Connect("178.33.213.54", 25565)
Dim stream As NetworkStream = client .GetStream
'Send Bytes
Dim sendBytes As [Byte]() = {&HFE}
stream.Write(sendBytes, 0, sendBytes.Length)
'Receive Bytes
Dim bytes(client .ReceiveBufferSize) As Byte
stream.Read(bytes, 0, CInt(leclient.ReceiveBufferSize))
'Convert it to ASCII
....
'Output it to Console
....
Here is the same code in PHP, python, and ruby.
php -> https://gist.github.com/1235274
python -> https://gist.github.com/1209061
ruby -> http://pastebin.com/q5zFPcXV
The documentation is here:
http://www.wiki.vg/Protocol#Server_List_Ping_.280xFE.29
Thanks in advance!
Vidhu
Tested and working.
Dim client As New System.Net.Sockets.TcpClient()
client.Connect("178.33.213.54", 25565)
Dim stream As System.Net.Sockets.NetworkStream = client.GetStream
'Send Bytes
Dim sendBytes As [Byte]() = {&HFE}
stream.Write(sendBytes, 0, sendBytes.Length)
''Receive Bytes
Dim bytes(client.ReceiveBufferSize) As Byte
stream.Read(bytes, 0, CInt(client.ReceiveBufferSize))
Dim sb As New System.Text.StringBuilder
For i As Integer = 3 To bytes.GetUpperBound(0) Step 2
Dim byt2(1) As Byte
byt2(0) = bytes(i + 1)
byt2(1) = bytes(i)
Dim ii As Integer = BitConverter.ToInt16(byt2, 0)
'sb.Append(Hex(ii)) 'debug
sb.Append(ChrW(ii))
Next i
MsgBox(sb.ToString)
stream.Close()