如何用vb实现读取本地计算机的IP地址??

请问VB中显示本地IP的代码???
2024-11-27 00:45:39
推荐回答(2个)
回答1:

If InStr(sIP, ".") = 0 Then
GetMACAddress = "Invaild IP Address."
Exit Function
End If

aIP = Split(sIP, ".", -1, vbTextCompare)
If UBound(aIP()) <> 3 Then
GetMACAddress = "Invaild IP Address."
Exit Function
End If

For X = 0 To UBound(aIP())
If Len(aIP(X)) > 3 Then
GetMACAddress = "Invaild IP Address"
Exit Function
End If

If IsNumeric(aIP(X)) = False Then
GetMACAddress = "Invaild IP Address"
Exit Function
End If

If InStr(aIP(X), ",") <> 0 Then
GetMACAddress = "Invaild IP Address"
Exit Function
End If

If CLng(aIP(X)) > 255 Then
GetMACAddress = "Invaild IP Address"
Exit Function
End If

If nIP = "" Then
nIP = String(3 - Len(aIP(X)), "0") & aIP(X)
Else
nIP = nIP & "." & String(3 - Len(aIP(X)), "0") & aIP(X)
End If
Next

sRtn = ""
myNcb.ncb_command = NCBRESET
bRet = Netbios(myNcb)
myNcb.ncb_command = NCBASTAT
myNcb.ncb_lana_num = 0
myNcb.ncb_callname = nIP & Chr(0)

Dim myASTAT As ASTAT, tempASTAT As ASTAT
Dim pASTAT As Long
myNcb.ncb_length = Len(myASTAT)

pASTAT = HeapAlloc(GetProcessHeap(), HEAP_GENERATE_EXCEPTIONS Or HEAP_ZERO_MEMORY, myNcb.ncb_length)
If pASTAT = 0 Then
GetMACAddress = "memory allcoation failed!"
Exit Function
End If

myNcb.ncb_buffer = pASTAT
bRet = Netbios(myNcb)

If bRet <> 0 Then
GetMACAddress = "Can not get the MAC Address from IP Address: " & sIP
Exit Function
End If

CopyMemory myASTAT, myNcb.ncb_buffer, Len(myASTAT)

Dim sTemp As String
Dim I As Long
For I = 0 To 5
sTemp = Hex(myASTAT.adapt.adapter_address(I))
If I = 0 Then
sRtn = IIf(Len(sTemp) < 2, "0" & sTemp, sTemp)
Else
sRtn = sRtn & Space(1) & IIf(Len(sTemp) < 2, "0" & sTemp, sTemp)
End If
Next
HeapFree GetProcessHeap(), 0, pASTAT
GetMACAddress = sRtn
End Function

Private Sub Command1_Click()
'修改IP地址即可
MsgBox GetMACAddress("192.168.0.1")
End Sub

回答2:

加载控件Microsoft Winsock Control 6.0
添加都窗体,在Form_Load()过程中:
Private Sub Form_Load()
msgbox "本地IP:" & Winsock1.LocalIP
End Sub