如何通过子网掩码计算网络ID?附VB.NET获取IP及掩码代码
计算IPv4对应的Network ID(附VB.NET实现)
嘿,我来帮你搞定这个网络ID的计算问题~
先搞懂原理:网络ID是怎么来的?
网络ID其实就是把你的IPv4地址和子网掩码做二进制按位与运算的结果。拿你给出的例子来拆解:
- IP地址:144.28.16.17 → 二进制:
10010000.00011100.00010000.00010001 - 子网掩码:255.255.240.0 → 二进制:
11111111.11111111.11110000.00000000
把每一位对应做与运算(规则:1&1=1,1&0=0,0&0=0),得到的二进制结果转成十进制就是:144.28.16.0——这就是你要的网络ID啦。
把计算逻辑整合到你的VB.NET代码里
我帮你写了一个可复用的计算函数,还把它整合到你现有的代码流程中,直接用就行:
第一步:添加通用计算函数
这个函数可以单独提取出来,以后需要计算网络ID时直接调用:
Private Function CalculateNetworkID(ipAddress As String, subnetMask As String) As String ' 将IP和子网掩码解析为字节数组 Dim ipBytes As Byte() = System.Net.IPAddress.Parse(ipAddress).GetAddressBytes() Dim maskBytes As Byte() = System.Net.IPAddress.Parse(subnetMask).GetAddressBytes() ' 校验是否为合法IPv4格式(必须是4字节) If ipBytes.Length <> 4 Or maskBytes.Length <> 4 Then Return "无效的IPv4地址或子网掩码" End If ' 执行按位与运算 Dim networkBytes(3) As Byte For i As Integer = 0 To 3 networkBytes(i) = CByte(ipBytes(i) And maskBytes(i)) Next ' 将字节数组转回IP字符串返回 Return New System.Net.IPAddress(networkBytes).ToString() End Function
第二步:整合到你的现有代码中
在你获取到子网掩码submark的位置,直接调用上面的函数就能得到网络ID:
Dim strHostName As String Dim strIPAddress As String Dim strMsg = "" strHostName = System.Net.Dns.GetHostName() strIPAddress = "" Dim iphe As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(strHostName) For Each ipheal As System.Net.IPAddress In iphe.AddressList If ipheal.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then strIPAddress = ipheal.ToString() For Each adapter As Net.NetworkInformation.NetworkInterface In Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces() For Each unicastIPAddressInformation As Net.NetworkInformation.UnicastIPAddressInformation In adapter.GetIPProperties().UnicastAddresses If unicastIPAddressInformation.Address.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then If strIPAddress.Equals(unicastIPAddressInformation.Address.ToString()) Then ' 获取子网掩码 Dim submark = unicastIPAddressInformation.IPv4Mask.ToString() ' 计算并获取网络ID Dim networkID = CalculateNetworkID(strIPAddress, submark) ' 组装结果信息(示例:可以输出到弹窗或日志) strMsg = $"IP地址:{strIPAddress}{Environment.NewLine}子网掩码:{submark}{Environment.NewLine}网络ID:{networkID}" MessageBox.Show(strMsg) End If End If Next Next Exit For End If Next
小提示
- 这个函数仅针对IPv4有效,如果以后需要处理IPv6,需要调整字节长度和运算逻辑
- 可以根据需求扩展异常处理,比如捕获IP格式解析失败的情况
内容的提问来源于stack exchange,提问作者D T
相关产品推荐
相关产品推荐

