I received a string over TCP socket. And this string looks something like this:
str = "10.100.200.200\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
How should I parse this into an IPAddress? If I do this,
IPAddress.TryParse(msg.nonTargetIP.Trim(), out ip);
it fails to parse.
What is simplest way to remove those trailing null's?
The other examples have shown you how to trim the string - but it would be better not to get the "bad" data to start with.
My guess is that you have code like this:
// Bad code
byte[] data = new byte[8192];
stream.Read(data, 0, data.Length);
string text = Encoding.ASCII.GetString(data);
That's ignoring the return value of Stream.Read
. Your code should be something like this instead:
// Better code
byte[] data = new byte[8192];
int bytesRead = stream.Read(data, 0, data.Length);
string text = Encoding.ASCII.GetString(data, 0, bytesRead);
Note that you should also check whether the stream has been closed, and don't assume you'll be able to read all the data in one call to Read
, or that one call to Write
at the other end corresponds to one call to Read
.
Of course it's entirely possible that this isn't the case at all - but you should really check whether the other end is trying to send these extra "null" bytes at the end of the data. It sounds unlikely to me.
IPAddress.TryParse(msg.nonTargetIp.Replace("\0", String.Empty).Trim(), out ip);
Alternatively reading up on Trim() you could do the following which is probably quicker:
IPAddress.TryParse(msg.nonTargetIp.TrimEnd(new char[] { '\0' } ), out ip);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With