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

ぐ巨炮叔叔 提交于 2019-12-23 12:49:58

问题


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?


回答1:


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);



回答2:


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.




回答3:


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




回答4:


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

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



回答5:


You could try string replacement instead of trimming:

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



回答6:


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).



来源:https://stackoverflow.com/questions/6683168/c-sharp-removing-trailing-0-from-ip-address-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!