单个网卡+有多个模拟LAN网络连接时如何正确获取网卡的LAN IP?

jessezappy jessezappy 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
因为想使用WinSockAPI来做TCP连接,于是找到了老马封装的一个自定义控件的WSAPI模块包,在只有一个本地连接的机器上运行一切正常,但是到了有多个LAN网络连接的机器上就无法准确定位真实网卡的IP(只有一块网卡,但是安装虚拟机后会生成几个虚拟LAN连接,见下图),导致绑定LAN IP 失败,就无法进行后续操作了.

里面有一个叫做: BindInternal 的过程需要用到真实网卡的IP,也就是上图中的"本地连接"的IP,但是那个包里面的: GetLocalIP 函数只能获取一个IP地址,而且不能保证是不是真实网卡的IP,于是找了个获取所有LAN连接的IP的函数来,但是还是无法区分到底那个IP才是我们需要的网卡的IP?请教各位是否有什么办法确定那个IP是网卡的?或者如何只获取真实网卡的IP?

我自己找的获取所有IP的函数如下:

我弱智的改了一下,将最后一个IP列表的IP输出,但是真实网卡的IP不可能每次都在最后一个....寒....

Private Function GetLocIP() As String
Dim hostname As String
Dim hostent_addr As Long
Dim host As HOSTENT
Dim hostip_addr As Long
Dim temp_ip_address() As Byte
Dim i As Integer
Dim ip_address As String

hostname = GetLocalHostName


hostent_addr = gethostbyname(hostname)

If hostent_addr = 0 Then
GetLocIP = vbNullString
Dim lngErrorCode As Long
lngErrorCode = Err.LastDllError
Err.Raise lngErrorCode, "CSocketMaster.GetLocalIP", GetErrorDescription(lngErrorCode)
Exit Function
End If

RtlMoveMemory host, hostent_addr, LenB(host)
RtlMoveMemory hostip_addr, host.hAddrList, 4

' MsgBox hostname

'get all of the IP address if machine is multi-homed

Do
ReDim temp_ip_address(1 To host.hLength)
RtlMoveMemory temp_ip_address(1), hostip_addr, host.hLength
ip_address = ""
For i = 1 To host.hLength
ip_address = ip_address & temp_ip_address(i) & "."
Next
ip_address = Mid$(ip_address, 1, Len(ip_address) - 1)

' MsgBox ip_address


host.hAddrList = host.hAddrList + LenB(host.hAddrList)
RtlMoveMemory hostip_addr, host.hAddrList, 4
Loop While (hostip_addr <> 0)
GetLocIP = ip_address
End Function


下面是老马封装的WSAPI包里面的LAN IP获取函数,只获取IP列表中的第一个IP....如果真实网卡的IP不在列表第一个的话就....

Private Function GetLocalIP() As String
Dim lngResult As Long
Dim lngPtrToIP As Long
Dim strLocalHost As String
Dim arrIpAddress(1 To 4) As Byte
Dim Count As Integer
Dim udtHostent As HOSTENT
Dim strIpAddress As String

strLocalHost = GetLocalHostName

lngResult = api_gethostbyname(strLocalHost)

If lngResult = 0 Then
GetLocalIP = vbNullString
Dim lngErrorCode As Long
lngErrorCode = Err.LastDllError
Err.Raise lngErrorCode, "CSocketMaster.GetLocalIP", GetErrorDescription(lngErrorCode)
Else
api_CopyMemory udtHostent, ByVal lngResult, LenB(udtHostent)
api_CopyMemory lngPtrToIP, ByVal udtHostent.hAddrList, 4
api_CopyMemory arrIpAddress(1), ByVal lngPtrToIP, 4

For Count = 1 To 4
strIpAddress = strIpAddress & arrIpAddress(Count) & "."
Next

strIpAddress = Left$(strIpAddress, Len(strIpAddress) - 1)
GetLocalIP = strIpAddress
End If
End Function

老马看到的话,随便说声:紫水晶论坛服务器好象又上不去了.
...全文

相关推荐

评论 11
收藏 已收藏
分享
返回顶部
jessezappy
API 1,488 成员 23,270 内容