Search code examples
c#stringsocketstcpclient

C# problem with string received on tcpclient socket


I have tcp client C# code. It works fine for connecting to any port and getting data. It works with linux/unix servers fine too. But in one case, when I connect to a linux server (openwrt), I can receive data but I can't show the string. The code shows that string contains what I want, but MessageBox.Show doesn't show the string.

What's the problem?

string ip = "192.168.0.1";
string command ="MT15";
string result = "None";

int i = 0;
int bytesRead;

byte[] rec_message = new byte[65535];

StringBuilder Whole_Message = new StringBuilder();
int port = 8889;

var client = new TcpClient();

NetworkStream ns;
int total = 0;

if (!client.ConnectAsync(ip, port).Wait(1000)) 
{ 
     result = "Failed"; 
}

byte[] byteTime = Encoding.ASCII.GetBytes(command);
ns = client.GetStream();
ns.Write(byteTime, 0, byteTime.Length);

// the string.contain Shows the string contains the mac address
while (!result.Contains("C2:04:28:00:5F:F1"))
{
    bytesRead = ns.Read(rec_message, 0, rec_message.Length);
    total = total + bytesRead;

    result = Encoding.ASCII.GetString(rec_message, 0, total);
    Whole_Message.AppendFormat("{0}", result);

    //row = Whole_Message.ToString().Split(',');
}

string r = Whole_Message.ToString();
// the string.contain returns true, so the string contains the mac address

if (r.Contains("C2:04:28:00:5F:F1"))
{
    MessageBox.Show(r);
}

client.Close();

But the MessageBox only shows "MT15"

The tcpdump packet sniff result :

18:06:21.430073 IP 192.168.0.2.6481 > 192.168.0.1.8889: tcp 4
E..,HX....cg%...%....Q".....5#v.P.@t....MT15..

18:06:21.439163 IP 192.168.0.1.8889 > 192.168.0.2.6481: tcp 0
E..(*.@.=..,%...%..."..Q5#v.....P....|..

18:06:21.475525 IP 192.168.0.1.8889 > 192.168.0.2.6481: tcp 23
E..?*.@.=...%...%..."..Q5#v.....P.......MT15..C2:04:28:00:5F:F1

The message is "MT15..C2:04:28:00:5F:F1" but the messagebox shows only "MT15" this not an issue with messagebox, I can't store and read to datatable or debug.write.


Solution

  • It sounds like your data has some null-characters in it, which some APIs (and especially: core Windows APIs like MessageBox) will treat as a C-style terminated string. Confusingly, not all APIs will do that - especially in managed code, where strings aren't expected to be null-terminated.

    As an example:

    MessageBox.Show("hello\0world");
    

    only shows hello in the message box:

    enter image description here

    When seeing null characters, a fundamental question should probably be asked, i.e. is this data really textual at all; if you're happy that it is, then you can probably just strip them:

    string s = ... // might contain null characters
    s = s.Replace("\0",""); // now it doesn't