如果用户的本地IP不是以10.80
开头,我的目标是让代码执行。
我找不到一种不容易出错的方法,例如:
这是我必须得到的I.P。:
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
iplabel.Text = localIP;
然后我尝试将其转换为int
以检查它是否<或>:
string ipstring = iplabel.Text.Replace(".", "");
int ipnum = int.Parse(ipstring);
if (ipnum > 1080000000 && ipnum < 1080255255)
{//stuff}
但问题是,如果有一个2位数的IP值,例如10.80.22.23
,它将无法正常工作,因为它检查的数字大于该范围。
有没有更好的解决方案来检查C#中int或IP地址的前x位数?
答案 0 :(得分:6)
你试过了吗?
bool IsCorrectIP = ( ipstring.StartsWith("10.80.") );
很抱歉,如果答案太简洁了。但那应该可以解决手头的问题。
答案 1 :(得分:2)
byte[] bytes = ipAddress.GetAddressBytes();
bool ok = bytes.Length >= 2 && bytes[0] == 10 && bytes[1] == 80;
答案 2 :(得分:1)
您可以直接检查IP的字节:
byte[] bytes = ip.GetAddressBytes();
// Check ipv4
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
if (bytes[0] == 10 && bytes[1] == 80) {
}
}
答案 3 :(得分:0)
@Flater是真的。您还可以使用此
bool IsCorrectIP = false;
string[] iparr = ipstring.Split(new char[] { '.' ,StringSplitOptions.RemoveEmptyEntries });
if(iparr[0] = "10" && iparr[1] == 80)
{
IsCorrectIP = true;
}
但即使我会选择@ Flater的解决方案:)