C # Removing end string '\ 0' from IP address string

I got the string through a TCP socket. And this line 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 do I parse this in IPAddress? If I do this

 IPAddress.TryParse(msg.nonTargetIP.Trim(), out ip); 

he does not understand.

What is the easiest way to remove these trailing null values?

+4
source share
7 answers
 IPAddress.TryParse(msg.nonTargetIp.Replace("\0", String.Empty).Trim(), out ip); 

Alternatively, by reading Trim () , you can do the following, which is probably faster:

 IPAddress.TryParse(msg.nonTargetIp.TrimEnd(new char[] { '\0' } ), out ip); 
+13
source

Other examples showed you how to trim a string, but it would be better not to start with "bad" data.

I assume you have code like this:

 // Bad code byte[] data = new byte[8192]; stream.Read(data, 0, data.Length); string text = Encoding.ASCII.GetString(data); 

This ignores the return value of Stream.Read . Instead, your code should look something like this:

 // Better code byte[] data = new byte[8192]; int bytesRead = stream.Read(data, 0, data.Length); string text = Encoding.ASCII.GetString(data, 0, bytesRead); 

Please note that you should also check if the stream was closed, and do not assume that you can read all the data in one Read call or one call to Write on the other end corresponds to one Read call.

Of course, it is entirely possible that this is not at all the case, but you really have to check if the other end is trying these extra "null" bytes at the end of the data. It seems unlikely to me.

+14
source

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

+5
source

The Trim method is more efficient than the Replace method.

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

You can try replacing the string instead of cropping:

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

You could just use TrimEnd() to do this:

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

Please note, however, that the example you provided contains an illegal IP address and will never be successfully resolved independently (300 → 255, each decimal number must be in the range from 2 to 255).

+1
source

Even if your intentions are not very clear; if all you need to do is get rid of these trailing "\ 0" then this line should do it and return the IPv4 address for you:

 str = str.Substring(0,str.LastIndexOf('.')+4); 

Hope this helps !!!

0
source

All Articles