这是我的代码,我可以获得IP地址和子网掩码,
Dim strHostName As String
Dim strIPAddress As String
Dim strMsg = ""
strHostName = System.Net.Dns.GetHostName()
strIPAddress = "" ' System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString()
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
'Subnet Mask
Dim submark = unicastIPAddressInformation.IPv4Mask.ToString()
End If
End If
Next
Next
Exit For
End If
Next
我得到的值是IP地址= 144.28.16.17和子网掩码= 255.255.240.0
如何获得如图所示的网络ID?
答案 0 :(得分:1)
对于IPv4,将ip转换为nums,然后将num转换为ip。像这样
Dim ip As Net.IPAddress
Dim mask As Net.IPAddress
Dim netID As Net.IPAddress
Dim strIP As String = "144.28.29.17"
Dim strMask As String = "255.255.240.0"
If Net.IPAddress.TryParse(strIP, ip) Then
If Net.IPAddress.TryParse(strMask, mask) Then
Dim inum As Integer = BitConverter.ToInt32(ip.GetAddressBytes, 0)
Dim mnum As Integer = BitConverter.ToInt32(mask.GetAddressBytes, 0)
inum = inum And mnum
netID = New Net.IPAddress(BitConverter.GetBytes(inum))
End If
End If