Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Removing trailing '\0' from IP Address string

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?

like image 812
ceonikka Avatar asked Nov 27 '22 00:11

ceonikka


2 Answers

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.

like image 108
Jon Skeet Avatar answered Dec 21 '22 10:12

Jon Skeet


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);
like image 24
Ian Avatar answered Dec 21 '22 09:12

Ian