开发者

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

I received a string over TCP so开发者_如何学JAVAcket. 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);


str = str.Replace("\0",""); should work just fine.


The Trim method is more efficient in comparison to the Replace method.

msg.nonTargetIP.Trim(new [] { '\0' });


You could try string replacement instead of trimming:

IPAddress.TryParse(msg.nonTargetIP.Replace("\0", ""), out ip);


You could just use TrimEnd() for this:

bool isIPAddress = IPAddress.TryParse(msg.nonTargetIP.nonTargetIP.TrimEnd('\0'), out ip);

Note however that the example you give contains an illegal IP address and will never successfully parse regardless (300 is > 255, each decimal number must be in the range from 2 to 255).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜