检查IP地址的前X位
Check first X digits of IP address
我的目标是让代码在用户的本地 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 位数是否有更好的解决方案?
你试过了吗:
bool IsCorrectIP = ( ipstring.StartsWith("10.80.") );
抱歉,如果答案过于简洁。但这应该可以解决手头的问题。
@Flater 说的很对。您还可以使用这个
bool IsCorrectIP = false;
string[] iparr = ipstring.Split(new char[] { '.' ,StringSplitOptions.RemoveEmptyEntries });
if(iparr[0] = "10" && iparr[1] == 80)
{
IsCorrectIP = true;
}
但即使是我也会选择@Flater 的解决方案:)
byte[] bytes = ipAddress.GetAddressBytes();
bool ok = bytes.Length >= 2 && bytes[0] == 10 && bytes[1] == 80;
可以直接查看IP的字节数:
byte[] bytes = ip.GetAddressBytes();
// Check ipv4
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
if (bytes[0] == 10 && bytes[1] == 80) {
}
}
我的目标是让代码在用户的本地 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 位数是否有更好的解决方案?
你试过了吗:
bool IsCorrectIP = ( ipstring.StartsWith("10.80.") );
抱歉,如果答案过于简洁。但这应该可以解决手头的问题。
@Flater 说的很对。您还可以使用这个
bool IsCorrectIP = false;
string[] iparr = ipstring.Split(new char[] { '.' ,StringSplitOptions.RemoveEmptyEntries });
if(iparr[0] = "10" && iparr[1] == 80)
{
IsCorrectIP = true;
}
但即使是我也会选择@Flater 的解决方案:)
byte[] bytes = ipAddress.GetAddressBytes();
bool ok = bytes.Length >= 2 && bytes[0] == 10 && bytes[1] == 80;
可以直接查看IP的字节数:
byte[] bytes = ip.GetAddressBytes();
// Check ipv4
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
if (bytes[0] == 10 && bytes[1] == 80) {
}
}