Received buffer of tcpclient contains not what expected - c#

I have a server side app written in C
struct recv_packet
{
int magic;
int code;
int length;
char *body;
};
char send_buff[1024+1] = "";
ZeroMemory(&send_buff, 1024);
memset(send_buff, 'A', 1024);
//send_buff[1024] = '\0';
recv_packet rcv_pkt = { 0 };
rcv_pkt.magic = MAGIC;
rcv_pkt.code = 0;
rcv_pkt.length = strlen(send_buff);
rcv_pkt.body = send_buff;
int size = sizeof(rcv_pkt.magic) + sizeof(rcv_pkt.code) + sizeof(rcv_pkt.length) + 1024+1;
if (send(ClientSocket, (char *)&rcv_pkt, size, 0) == SOCKET_ERROR)
{
printf("Error %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
On the other side i grab this packet like this:
public struct recv_packet
{
public int magic;
public int code;
public int length;
public byte[] body;
};
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int port = 4000;
TcpClient client = new TcpClient("127.0.0.1", 4000);
NetworkStream nws = client.GetStream();
BinaryWriter bw = new BinaryWriter(nws);
BinaryReader br = new BinaryReader(nws);
byte[] buff = new byte[512];
send_packet pkt = new send_packet();
pkt.magic = magic;
pkt.cmd = (int)command.MOVE_MOUSE;
while (true)
{
bw.Write(pkt.magic);
bw.Write(pkt.cmd);
//br.Read(buff, 0, 512);
recv_packet rcv_pkt = new recv_packet();
rcv_pkt.magic = br.ReadInt32();
rcv_pkt.code = br.ReadInt32();
rcv_pkt.length = br.ReadInt32();
rcv_pkt.body = br.ReadBytes(rcv_pkt.length);
//string str = rcv_pkt.length.ToString();
string str = System.Text.Encoding.Default.GetString(rcv_pkt.body);
MessageBox.Show(str);
}
}
So it suppose that body will have only '65', but instead I've got some trash in it.
Why could this happen? Thank you for your time.

As I understood there are few ways of resolving this problem - one of them is to redecrlare struct a little bit and then creare a buffer, where all structure elements will be fitted one-by-one. So the solution looks like this:
char send_buff[1024+1] = "";
ZeroMemory(&send_buff, 1025);
memset(send_buff, 'A', 1024);
recv_packet *rcv_pkt = (recv_packet *)malloc(sizeof(recv_packet)+1024+1);
//recv_packet rcv_pkt = { 0 };
rcv_pkt->magic = MAGIC;
rcv_pkt->code = 0;
rcv_pkt->length = strlen(send_buff);
memcpy(rcv_pkt->body, send_buff, 1025);
int size = sizeof(rcv_pkt->magic) + sizeof(rcv_pkt->code) + sizeof(rcv_pkt->length) + 1024 + 1;
//printf("%d", size);
//getchar();
//return 0;
//if (send(ClientSocket, rcv_pkt.body, rcv_pkt.length, 0) == SOCKET_ERROR)
if (send(ClientSocket, (char *)rcv_pkt, size, 0) == SOCKET_ERROR)

Related

Retrying Method

I am communicating with a device via UDP, I send a message and I receive the response.
public byte[] Rx_message = new byte[12];
public byte[] packedMessage2 = new byte[12];
public IPEndPoint sendEndPoint;
public void senderUdpClient(byte Type, byte CommandC, byte CodeCmd, Int32 X, Int32 Y)
{
string serverIP = "192.168.2.11";
int sendPort = 40960;
int receivePort = 40961;
var span = new Span<byte>(packedMessage2);
span[0] = Type;
span[1] = CommandC;
span[2] = CodeCmd;
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(3, 4), X);
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(7, 4), Y);
var sum = unchecked((byte)packedMessage2.Take(11).Sum(x => x));
span[11] = sum;
sendEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), sendPort);
try
{
UdpClient senderClient = new UdpClient();
senderClient.Connect(this.sendEndPoint);
senderClient.Send(packedMessage2, packedMessage2.Length);
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
UdpClient receivingUdpClient = new UdpClient(receivePort);
receivingUdpClient.Client.ReceiveTimeout = 50;
// receive message
Rx_message = receivingUdpClient.Receive(ref RemoteIpEndPoint);
senderClient.Close();
receivingUdpClient.Close();
}
catch (Exception ex)
{
}
}
I want to add a retry mechanism if the equipment does not respond in the event of a network problem,
(if I have an error: Rx_message [0] = -1 and if all goes well Rx_message [0] = 2)
Normally I should do 2 retry if I can connect I continue, otherwise I display an error message
public byte[] Rx_message = new byte[12];
public byte[] packedMessage2 = new byte[12];
public IPEndPoint sendEndPoint;
public int Connected = 0;
public void senderUdpClient(byte Type, byte CommandC, byte CodeCmd, Int32 X, Int32 Y)
{
string serverIP = "192.168.2.11";
int sendPort = 40960;
int receivePort = 40961;
var span = new Span<byte>(packedMessage2);
span[0] = Type;
span[1] = CommandC;
span[2] = CodeCmd;
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(3, 4), X);
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(7, 4), Y);
var sum = unchecked((byte)packedMessage2.Take(11).Sum(x => x));
span[11] = sum;
sendEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), sendPort);
try
{
for(int i = 0; i< 2; i++)
{
UdpClient senderClient = new UdpClient();
senderClient.Connect(this.sendEndPoint);
senderClient.Send(packedMessage2, packedMessage2.Length);
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
UdpClient receivingUdpClient = new UdpClient(receivePort);
receivingUdpClient.Client.ReceiveTimeout = 50;
// receive message
Rx_message = receivingUdpClient.Receive(ref RemoteIpEndPoint);
//first case where it is connected and I receive my answer correctly
if (Rx_message[0] == 2)
{
Connected = 1;
break;
}
//if I can't connect
if (Connected == 0)
{
//first try
if (i < 1)
{
Thread.Sleep(20);
continue;
}
//second try
if (i == 1)
{
//these two lines I put it just so that the code goes to try and shows me the error code
receivingUdpClient.Client.ReceiveTimeout = 1500;
Rx_message = receivingUdpClient.Receive(ref RemoteIpEndPoint);
}
}
senderClient.Close();
receivingUdpClient.Close();
}
}
catch (Exception ex)
{
if (Connected == 0)
{
MessageBox.Show("Error Connection");
}
sbyte type_message = Convert.ToSByte(Rx_message[0]);
if (type_message == -1)
{
if (Rx_message[3] == 1)
{
MessageBox.Show("Type invalide");
}
if (Rx_message[3] == 2)
{
MessageBox.Show("Commande invalide");
}
if (Rx_message[3] == 3)
{
MessageBox.Show("Argument invalide!");
}
if (Rx_message[3] == 4)
{
MessageBox.Show("Erreur CS!");
}
}
}
}
Here is the code I tried to do, once it gets to the reading line
Rx_message = receivingUdpClient.Receive(ref RemoteIpEndPoint);
he goes directly to Catch I don't know how I can force him to continue the code, otherwise someone can help me improve this mechanism

My symmetric encryption adds data to my rsa key I want to save and load encrypted

Currently I am trying to implement a save function for my RSA key with the help of bouncycastle. I am running into problems if I try to save my public or private key encrypted and load it afterwards.
As a little example here the original public key:
305C300D06092A864886F70D0101010500034B00304802410096B4751049165D1E046063EA22E8FFA0F90AE1DD997A3876DA5F79C7DE97951F009AC9ACA3EB91114F8A32C04F48293B6665CD6DD5C406C81CD13270A2AB61130203010001
What I get after loading it (it adds 4 zeroes, bigger key means more zeroes added):
305C300D06092A864886F70D0101010500034B00304802410096B4751049165D1E046063EA22E8FFA0F90AE1DD997A3876DA5F79C7DE97951F009AC9ACA3EB91114F8A32C04F48293B6665CD6DD5C406C81CD13270A2AB611302030100010000
I found out it has something to do with my implementation of the symmetric encryption and the padding used there. Normal text no matter how long it is just works fine without extra data getting added.
This is the code I am using for my AES encryption:
Encryption
byte[] outputBytes = new byte[0];
AesEngine aesengine = new AesEngine();
CbcBlockCipher aesblockCipher = new CbcBlockCipher(aesengine);
PaddedBufferedBlockCipher aescipher = new PaddedBufferedBlockCipher(aesblockCipher);
KeyParameter aeskeyParameter = new KeyParameter(Hash.HashDataBlock(password, Hash.HashAlgorithm.SHA3).Bytes);
aescipher.Init(true, aeskeyParameter);
outputBytes = new byte[aescipher.GetOutputSize(inputBytes.Bytes.Length)];
int aeslength = aescipher.ProcessBytes(inputBytes.Bytes, outputBytes, 0);
aescipher.DoFinal(outputBytes, aeslength);
Decryption
byte[] inputBytes = input.Bytes;
byte[] outputBytes = new byte[0];
AesEngine aesengine = new AesEngine();
CbcBlockCipher aesblockCipher = new CbcBlockCipher(aesengine);
PaddedBufferedBlockCipher aescipher = new PaddedBufferedBlockCipher(aesblockCipher);
KeyParameter aeskeyParameter = new KeyParameter(Hash.HashDataBlock(password, Hash.HashAlgorithm.SHA3).Bytes);
aescipher.Init(false, aeskeyParameter);
outputBytes = new byte[aescipher.GetOutputSize(inputBytes.Length)];
int aeslength = aescipher.ProcessBytes(inputBytes, outputBytes, 0);
aescipher.DoFinal(outputBytes, aeslength);
My Functions to save and load the keys. The DataBlock class just converts data to needed formats like UTF8, Base64 or just byte arrays:
public static void SaveKeyEncrypted(DataBlock key, string path, DataBlock password)
{
StreamWriter sw = new StreamWriter(path);
DataBlock encrypted = SymmetricEncryption.Encrypt(key, password, SymmetricEncryption.SymmetricAlgorithms.AES);
sw.Write(encrypted.Base64);
sw.Close();
}
public static DataBlock ReadKeyEncrypted(string path, DataBlock password)
{
StreamReader sr = new StreamReader(path);
DataBlock readData = new DataBlock(sr.ReadLine(), DataBlock.DataType.Base64);
sr.Close();
return SymmetricEncryption.Decrypt(readData, password, SymmetricEncryption.SymmetricAlgorithms.AES);
}
For reproduction my other code that has to do with this problem:
public class DataBlock
{
private byte[] _data;
public DataBlock()
{
this._data = new byte[0];
}
public enum DataType
{
UTF8,
UTF7,
UTF32,
ASCII,
Unicode,
Hex,
Base64,
Base32
}
public DataBlock(string data, DataType dataType) : this()
{
switch (dataType)
{
case DataType.UTF8:
this._data = Encoding.UTF8.GetBytes(data);
break;
case DataType.UTF7:
this._data = Encoding.UTF7.GetBytes(data);
break;
case DataType.UTF32:
this._data = Encoding.UTF32.GetBytes(data);
break;
case DataType.ASCII:
this._data = Encoding.ASCII.GetBytes(data);
break;
case DataType.Unicode:
this._data = Encoding.Unicode.GetBytes(data);
break;
case DataType.Hex:
this._data = new byte[data.Length / 2];
for (int i = 0; i < data.Length; i += 2)
{
this._data[i / 2] = Convert.ToByte(data.Substring(i, 2), 16);
}
break;
case DataType.Base64:
this._data = Convert.FromBase64String(data);
break;
case DataType.Base32:
this._data = this.FromBase32String(data);
break;
}
}
public DataBlock(byte[] data)
{
this._data = data;
}
public string UTF8
{
get
{
return Encoding.UTF8.GetString(this._data);
}
}
public string UTF7
{
get
{
return Encoding.UTF7.GetString(this._data);
}
}
public string UTF32
{
get
{
return Encoding.UTF32.GetString(this._data);
}
}
public string ASCII
{
get
{
return Encoding.ASCII.GetString(this._data);
}
}
public string Unicode
{
get
{
return Encoding.Unicode.GetString(this._data);
}
}
public string Hex
{
get
{
return BitConverter.ToString(this._data).Replace("-", "");
}
}
public string Base64
{
get
{
return Convert.ToBase64String(this._data);
}
}
public string Base32
{
get
{
return this.ToBase32String(this._data);
}
}
public byte[] Bytes
{
get
{
return this._data;
}
}
private string ValidChars = "QAZ2WSX3" + "EDC4RFV5" + "TGB6YHN7" + "UJM8K9LP";
private string ToBase32String(byte[] bytes)
{
StringBuilder sb = new StringBuilder();
byte index;
int hi = 5;
int currentByte = 0;
while (currentByte < bytes.Length)
{
if (hi > 8)
{
index = (byte)(bytes[currentByte++] >> (hi - 5));
if (currentByte != bytes.Length)
{
index = (byte)(((byte)(bytes[currentByte] << (16 - hi)) >> 3) | index);
}
hi -= 3;
}
else if (hi == 8)
{
index = (byte)(bytes[currentByte++] >> 3);
hi -= 3;
}
else
{
index = (byte)((byte)(bytes[currentByte] << (8 - hi)) >> 3);
hi += 5;
}
sb.Append(ValidChars[index]);
}
return sb.ToString();
}
public byte[] FromBase32String(string str)
{
int numBytes = str.Length * 5 / 8;
byte[] bytes = new Byte[numBytes];
str = str.ToUpper();
int bit_buffer;
int currentCharIndex;
int bits_in_buffer;
if (str.Length < 3)
{
bytes[0] = (byte)(ValidChars.IndexOf(str[0]) | ValidChars.IndexOf(str[1]) << 5);
return bytes;
}
bit_buffer = (ValidChars.IndexOf(str[0]) | ValidChars.IndexOf(str[1]) << 5);
bits_in_buffer = 10;
currentCharIndex = 2;
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = (byte)bit_buffer;
bit_buffer >>= 8;
bits_in_buffer -= 8;
while (bits_in_buffer < 8 && currentCharIndex < str.Length)
{
bit_buffer |= ValidChars.IndexOf(str[currentCharIndex++]) << bits_in_buffer;
bits_in_buffer += 5;
}
}
return bytes;
}
}
Function to generate a keypair
public static DataBlock[] GenerateKeyPair(KeyPairSize keyPairSize)
{
RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), (int) keyPairSize));
AsymmetricCipherKeyPair keyPair = keyPairGenerator.GenerateKeyPair();
PrivateKeyInfo pkInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
DataBlock[] keyPairData = new DataBlock[2];
keyPairData[0] = new DataBlock(pkInfo.GetDerEncoded());
keyPairData[1] = new DataBlock(info.GetDerEncoded());
return keyPairData;
}
Code to reproduce the error:
DataBlock[] keyPair = AsymmetricEncryption.GenerateKeyPair(AsymmetricEncryption.KeyPairSize.Bits512);
DataBlock pass = new DataBlock("1234", DataBlock.DataType.UTF8);
DataBlock orig = new DataBlock("Hello World", DataBlock.DataType.UTF8);
DataBlock encrypted = AsymmetricEncryption.Encrypt(orig, keyPair[1]);
AsymmetricEncryption.SaveKeyEncrypted(keyPair[0], "D:\\privateenc", pass);
AsymmetricEncryption.SaveKeyEncrypted(keyPair[1], "D:\\publicenc", pass);
DataBlock privateKey = AsymmetricEncryption.ReadKeyEncrypted("D:\\privateenc", pass);
DataBlock publicKey = AsymmetricEncryption.ReadKeyEncrypted("D:\\publicenc", pass);
DataBlock decrypted = AsymmetricEncryption.Decrypt(encrypted, privateKey);
Console.WriteLine(decrypted.UTF8);
The encryption/decryption method is not needed because the error already happens after reading the encrypted key on my harddrive.
Why/where is the extra data added and how can I fix it?
I was able to fix it by adding the initial byte array length of the key to the encrypted text and read it later on. In the read function I cut everything after the original size of the key.
The main problem is still present and this is just a workaround.

Read mobile phone book using obex in c#

i have a OBEXConnect and OBEXRequest custom functions, i am not using library for it
OBEXConnect function is as following
private bool OBEXConnect()
{
//send client request
byte[] ConnectPacket = new byte[7];
ConnectPacket[0] = 0x80; // Connect
ConnectPacket[1] = 0x00; // Packetlength Hi Byte
ConnectPacket[2] = 0x07; // Packetlength Lo Byte
ConnectPacket[3] = 0x10; // Obex v1
ConnectPacket[4] = 0x00; // no flags
ConnectPacket[5] = 0x20; // 8k max packet size Hi Byte
ConnectPacket[6] = 0x00; // 8k max packet size Lo Byte
stream.Write(ConnectPacket,0,ConnectPacket.Length);
//listen for server response
byte[] ReceiveBufferA = new byte[3];
stream.Read(ReceiveBufferA,0,3);
if (ReceiveBufferA[0] == 160) // 0xa0
{
//success, decode rest of packet
int plength = (0xff * ReceiveBufferA[1]) + ReceiveBufferA[2]; //length of packet is...
//listen for rest of packet
byte[] ReceiveBufferB = new byte[plength-3];
stream.Read(ReceiveBufferB,0,plength-3);
int obver = ReceiveBufferB[0]; //server obex version (16 = v1.0)
int cflags = ReceiveBufferB[1]; //connect flags
int maxpack = (0xff * ReceiveBufferB[2]) + ReceiveBufferB[3]; //max packet size
return true;
}
else
{
return false;
}
}
and here is OBEXRequest function
private int OBEXRequest(string tReqType, string tName, string tType, string tFileContent)
{
//send client request
int i;
int offset;
int packetsize;
byte reqtype = 0x82;
int tTypeLen = 0x03;
int typeheadsize;
int typesizeHi = 0x00;
int typesizeLo = 0x03;
//tName = "contact.vcf";
//tType = "text/x-vCard";
//tFileContent = "BEGIN:VCARD\r\nVERSION:2.1\r\nN:;aardvark\r\nFN:aardvark\r\nEND:VCARD\r\n";
if (tReqType == "GET")
{
reqtype = 0x83; // 131 GET-Final
}
if (tReqType == "PUT")
{
reqtype = 0x82; // 130 PUT-Final
}
packetsize = 3;
//Name Header
int tNameLength = tName.Length;
int nameheadsize = (3 + (tNameLength*2) + 2);
int namesizeHi = (nameheadsize & 0xff00)/0xff;
int namesizeLo = nameheadsize & 0x00ff;
packetsize = packetsize + nameheadsize;
if (tType != "")
{
//Type Header
tTypeLen = tType.Length;
typeheadsize = 3 + tTypeLen + 1;
typesizeHi = (typeheadsize & 0xff00)/0xff;
typesizeLo = typeheadsize & 0x00ff;
packetsize = packetsize + typeheadsize;
}
//Body
int fileLen = tFileContent.Length;
int fileheadsize = 3 + fileLen ;
int filesizeHi = (fileheadsize & 0xff00)/0xff;;
int filesizeLo = fileheadsize & 0x00ff;;
packetsize = packetsize + fileheadsize;
int packetsizeHi = (packetsize & 0xff00)/0xff;
int packetsizeLo = packetsize & 0x00ff;
byte[] tSendByte = new byte[packetsize];
//PUT-final Header
tSendByte[0] = reqtype; // Request type e.g. PUT-final 130
tSendByte[1] = Convert.ToByte(packetsizeHi); // Packetlength Hi
tSendByte[2] = Convert.ToByte(packetsizeLo); // Packetlength Lo
offset = 2;
//Name Header
tSendByte[offset+1] = 0x01; // HI for Name header
tSendByte[offset+2] = Convert.ToByte(namesizeHi); // Length of Name header (2 bytes per char)
tSendByte[offset+3] = Convert.ToByte(namesizeLo); // Length of Name header (2 bytes per char)
// Name+\n\n in unicode
byte[] tNameU = System.Text.Encoding.BigEndianUnicode.GetBytes(tName);
tNameU.CopyTo(tSendByte,offset+4);
offset = offset + 3 + (tNameLength*2);
tSendByte[offset+1] = 0x00; // null term
tSendByte[offset+2] = 0x00; // null term
offset = offset + 2;
if (tType != "")
{
//Type Header
tSendByte[offset+1] = 0x42; // HI for Type Header 66
tSendByte[offset+2] = Convert.ToByte(typesizeHi); // Length of Type Header
tSendByte[offset+3] = Convert.ToByte(typesizeLo); // Length of Type Header
for (i=0;i<=(tTypeLen-1);i++)
{
tSendByte[offset+4+i] = Convert.ToByte(Convert.ToChar(tType.Substring(i,1)));
}
tSendByte[offset+3+tTypeLen+1] = 0x00; // null terminator
offset = offset+3+tTypeLen+1;
}
//Body
tSendByte[offset+1] = 0x49; //HI End of Body 73
tSendByte[offset+2] = Convert.ToByte(filesizeHi); //
tSendByte[offset+3] = Convert.ToByte(filesizeLo); //1k payload + 3 for HI header
for (i=0;i<=(fileLen-1);i++)
{
tSendByte[offset+4+i] = Convert.ToByte(Convert.ToChar(tFileContent.Substring(i,1)));
}
//tSendByte[offset+4+fileLen] = 0x00; // null terminator
offset = offset+3+fileLen;
stream.Write(tSendByte,0,tSendByte.Length );
//listen for server response
//TODO: can hang here forever waiting response...
bool x = stream.DataAvailable; // changed bluetoothclient - public NetworkStream GetStream()
byte[] tArray4 = new byte[3];
stream.Read(tArray4,0,3);
x = stream.DataAvailable;
if (tArray4[0] == 160) // 0xa0
{
int plength = (tArray4[1] * 256) + tArray4[2] - 3;
byte[] tArray5 = new byte[plength];
if (plength >0)
{
stream.Read(tArray5,0,plength);
//TODO: data in returned packet to deal with
}
return 160;
}
if (tArray4[0] == 197) // 0xc5 Method not allowed
{
return 197;
}
if (tArray4[0] == 192) // 0xc0 Bad Request
{
return 192;
}
return 0;
}
i want to read the phone book of mobile but i not succeeded yet
i try on one samsung mobile it gives error bad request i follow the solutions above mentioned but when name = null then obexrequest function gives error
when i try it on huawei mobile it gives unknown error
i try this code as well it throw error that this method is not implemented
Read contacts using obex in c#
i call these functions like this
string tName = "";
string tType = "text/x-vCard";
string tFileContent = "";
int result = OBEXRequest("GET",tName,tType,tFileContent);
switch (result)
{
case 160: // 0xa0
addtolog("OK");
break;
case 197: // 0xc5
addtolog("Method not allowed");
break;
case 192: // 0xc0
addtolog("Bad Request");
break;
default:
addtolog("Other Error");
break;
}
can any body point out my mistake

Serial communication and CRLF C#

i Have question about CRLF after sending a string to the serial port.
Let me explain what im trying to do, Under here there is an example.
[ACR] CRLF
10:90 CRLF
11:20 CRLF
12:2.1 CRLF
That is what im trying to do but i cant get anywhere, Can someone help me with this.
i think i have to do the CRLF to start a newline but if you have other suggestions they will be more then welcome
This is what i've done:
Code:
private void SendMessageTest()
{
var content = _durCleaningTextbox.Text;
byte[] array = ComPort.StringToBytes(content);
_comport.WriteBytes(array);
_comport.ReadBytes(array, array.Length, 1000);
string result = Encoding.ASCII.GetString(array);
MessageBox.Show(result);
}
using System;
using System.IO;
using System.Text;
using System.IO.Ports;
namespace Communication
{
public class ComPort
{
private readonly SerialPort _serialPort;
public ComPort(string portName, int baudRate)
{
_serialPort = new SerialPort();
_serialPort.PortName = portName;
_serialPort.BaudRate = baudRate;
_serialPort.StopBits = StopBits.One;
_serialPort.DataBits = 8;
_serialPort.Parity = Parity.None;
_serialPort.Handshake = Handshake.None;
// _serialPort.WriteBufferSize = 1;
_serialPort.DtrEnable = true;
_serialPort.RtsEnable = true;
_serialPort.Open();
_serialPort.ReadTimeout = 20000;
_serialPort.WriteTimeout = 20000;
}
public void Clear()
{
while (ReadByte() != -1)
continue;
}
private byte[] _array = new byte[] {0};
public void WriteByte(byte value)
{
_array[0] = value;
_serialPort.Write(_array, 0, 1);
// _serialPort.BaseStream.WriteByte(value);
_serialPort.BaseStream.Flush();
}
public void WriteBytes(byte[] array)
{
_serialPort.Write(array, 0, array.Length);
}
public void WriteBytes(byte[] array, int index, int length )
{
_serialPort.Write(array, index, length);
}
private int _readTimeOut = -1;
public int ReadByte(int timeOut = 200)
{
if (timeOut != _readTimeOut)
_serialPort.ReadTimeout = _readTimeOut = timeOut;
try
{
//return _serialPort.BaseStream.ReadByte();
return _serialPort.ReadByte();
// _serialPort.Read(array, 0, 1);
// return array[0];
}
catch (TimeoutException)
{
return -1;
}
}
public int ReadBytes(byte[] array, int length, int timeOut = 200)
{
if (timeOut != _readTimeOut)
_serialPort.ReadTimeout = _readTimeOut = timeOut;
try
{
//return _serialPort.BaseStream.ReadByte();
int bytesRead = 0;
while ( bytesRead < length )
bytesRead += _serialPort.Read(array, bytesRead, length - bytesRead);
// _serialPort.Read(array, 0, 1);
// return array[0];
return bytesRead;
}
catch (TimeoutException)
{
return -1;
}
}
/// <summary>
/// sends string followed by CR - LF
/// </summary>
/// <param name="line"></param>
public void WriteLine(String line)
{
WriteBytes(StringToBytes(line + "\r\n"));
}
public static byte[] StringToBytes(string input)
{
return Encoding.ASCII.GetBytes(input);
}
public void Close()
{
try
{
_serialPort.DtrEnable = false;
_serialPort.RtsEnable = false;
_serialPort.Close();
}
catch(IOException)
{
}
}
public bool Dtr
{
get { return _serialPort.DtrEnable; }
set { _serialPort.DtrEnable = value; }
}
public bool Rts
{
get { return _serialPort.RtsEnable; }
set { _serialPort.RtsEnable = value; }
}
}
}
byte[] array = ComPort.StringToBytes(content + "\r\n");
Or use your WriteLine method which already does this. So:
byte[] array = ComPort.StringToBytes(content);
_comport.WriteBytes(array);
Becomes:
_comport.WriteLine(content);
You need send the commands CR (Carriage Return) and LF (Line Feed, or new line).
For this is just to send your command plus the the CR and LF like this:
string command = "myCommand";
port.write(string.format("{0}\r\n", command));
\r\n = CR + LF -> Used as a new line character in Windows

how to calculate CRC value for a file in C#.net?

i want to calculate the CRC value for a file using 32-bit algorithm in C#.net....
Algorithm is straightforward (rewritten from c++)
class Crc32
{
public static uint CountCrc(byte[] pBuf)
{
// Table of CRC-32's of all single byte values
uint[] crctab = new uint[] {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
0x2d02ef8d
};
uint c = 0xffffffff; // begin at shift register contents
int i, n = pBuf.Length;
for (i = 0; i < n; i++)
{
c = crctab[((int)c ^ pBuf[i]) & 0xff] ^ (c >> 8);
}
return c ^ 0xffffffff;
}
}
I used Crc32.NET in BackgroundWorker:
private void Crc_DoWork(object sender, DoWorkEventArgs e)
{
FileInfo file = e.Argument as FileInfo;
uint r = 0;
using (var s = file.OpenRead())
{
byte[] buff = new byte[1024];
int len = s.Read(buff, 0, buff.Length);
r = Crc32Algorithm.Compute(buff, 0, len);
while ((len = s.Read(buff, 0, buff.Length)) > 0)
r = Crc32Algorithm.Append(r, buff, 0, len);
}
e.Result = Convert.ToString(r, 16).ToUpper();
}

Categories

Resources