vba 如何找回这台电脑的IP地址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/828496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:45:45  来源:igfitidea点击:

How to retrieve this computer's IP address?

excelvbaexcel-vbamsinet

提问by jpinto3912

What is the least cumbersome (module-inclusion, code lenght, etc) way to retrieve the machine IP address (of the first interface open)? I know of some solutions using MSINET, but I believe we can do better. Don't reply

检索机器 IP 地址(打开的第一个接口的)最不麻烦(模块包含、代码长度等)的方法是什么?我知道一些使用 MSINET 的解决方案,但我相信我们可以做得更好。不要回复

Function HomeIP() as Atring
HomeIP= "127.0.0.1"
End Function

because it's not that funny... or correct. The scenario is a question wiht a document ID featureI'm trying to build a reply for.

因为它不是那么有趣......或者正确。该场景是一个我正在尝试为其构建回复的文档 ID 功能的问题。

回答by Helen

Here's an adapted example from Technet:

这是来自Technet的改编示例:

Function GetIPAddress()
    Const strComputer As String = "."   ' Computer name. Dot means local computer
    Dim objWMIService, IPConfigSet, IPConfig, IPAddress, i
    Dim strIPAddress As String

    ' Connect to the WMI service
    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\" & strComputer & "\root\cimv2")

    ' Get all TCP/IP-enabled network adapters
    Set IPConfigSet = objWMIService.ExecQuery _
        ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE")

    ' Get all IP addresses associated with these adapters
    For Each IPConfig In IPConfigSet
        IPAddress = IPConfig.IPAddress
        If Not IsNull(IPAddress) Then
            strIPAddress = strIPAddress & Join(IPAddress, ", ")
        End If
    Next

    GetIPAddress = strIPAddress
End Function

It requires that you have Microsoft WMI Scripting Library in the project's references.

它要求您在项目的引用中具有 Microsoft WMI 脚本库。

回答by Adam Ralph

A couple of examples I found:-

我发现了几个例子:-

http://www.everythingaccess.com/tutorials.asp?ID=Get-all-IP-Addresses-of-your-machine

http://www.everythingaccess.com/tutorials.asp?ID=Get-all-IP-Addresses-of-your-machine

http://puremis.net/excel/code/079.shtml

http://puremis.net/excel/code/079.shtml

EDIT

编辑

Here is the code from the first link with slight modification

这是第一个链接的代码,稍作修改

Option Explicit

' VBA MODULE: Get all IP Addresses of your machine
' (c) 2005 Wayne Phillips (http://www.everythingaccess.com)
' Written 18/05/2005
'
' REQUIREMENTS: Windows 98 or above, Access 97 and above
'
' Please read the full tutorial here:
' http://www.everythingaccess.com/tutorials.asp?ID=Get-all-IP-Addresses-of-your-machine
'
' Please leave the copyright notices in place.
' Thank you.
'
'Option Compare Database

'A couple of API functions we need in order to query the IP addresses in this machine
Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Public Declare Function GetIpAddrTable Lib "Iphlpapi" (pIPAdrTable As Byte, pdwSize As Long, ByVal Sort As Long) As Long

'The structures returned by the API call GetIpAddrTable...
Type IPINFO
    dwAddr As Long         ' IP address
    dwIndex As Long         ' interface index
    dwMask As Long         ' subnet mask
    dwBCastAddr As Long     ' broadcast address
    dwReasmSize As Long    ' assembly size
    Reserved1 As Integer
    Reserved2 As Integer
End Type

Public Function ConvertIPAddressToString(longAddr As Long) As String

    Dim IPBytes(3) As Byte
    Dim lngCount As Long

    'Converts a long IP Address to a string formatted 255.255.255.255
    'Note: Could use inet_ntoa instead

    CopyMemory IPBytes(0), longAddr, 4 ' IP Address is stored in four bytes (255.255.255.255)

    'Convert the 4 byte values to a formatted string
    While lngCount < 4

        ConvertIPAddressToString = ConvertIPAddressToString + _
                                    CStr(IPBytes(lngCount)) + _
                                    IIf(lngCount < 3, ".", "")

        lngCount = lngCount + 1

    Wend

End Function

Public Function GetFirstNonLocalIPAddress()

    Dim Ret As Long, Tel As Long
    Dim bytBuffer() As Byte
    Dim IPTableRow As IPINFO
    Dim lngCount As Long
    Dim lngBufferRequired As Long
    Dim lngStructSize As Long
    Dim lngNumIPAddresses As Long
    Dim strIPAddress As String

On Error GoTo ErrorHandler:

    Call GetIpAddrTable(ByVal 0&, lngBufferRequired, 1)

    If lngBufferRequired > 0 Then

        ReDim bytBuffer(0 To lngBufferRequired - 1) As Byte

        If GetIpAddrTable(bytBuffer(0), lngBufferRequired, 1) = 0 Then

            'We've successfully obtained the IP Address details...

            'How big is each structure row?...
            lngStructSize = LenB(IPTableRow)

            'First 4 bytes is a long indicating the number of entries in the table
            CopyMemory lngNumIPAddresses, bytBuffer(0), 4

            While lngCount < lngNumIPAddresses

                'bytBuffer contains the IPINFO structures (after initial 4 byte long)
                CopyMemory IPTableRow, _
                            bytBuffer(4 + (lngCount * lngStructSize)), _
                            lngStructSize

                strIPAddress = ConvertIPAddressToString(IPTableRow.dwAddr)

                If Not ((strIPAddress = "127.0.0.1")) Then

                    GetFirstNonLocalIPAddress = strIPAddress
                    Exit Function

                End If

                lngCount = lngCount + 1

            Wend

        End If

    End If

Exit Function

ErrorHandler:
    MsgBox "An error has occured in GetIPAddresses():" & vbCrLf & vbCrLf & _
            Err.Description & " (" & CStr(Err.Number) & ")"

End Function

回答by sybreon

You could execute the shell command ipconfigand parse the returned results?

你可以执行shell命令ipconfig并解析返回的结果吗?

回答by THEn

There is another easy way using ipconfig. http://www.vbaexpress.com/kb/getarticle.php?kb_id=537

还有另一种使用 ipconfig 的简单方法。 http://www.vbaexpress.com/kb/getarticle.php?kb_id=537

回答by barrowc

nbtstat -nmight do the job on XP anyway. Not sure about other Windows versions or about localisation in other languages. Partial sample output:

nbtstat -n无论如何都可以在 XP 上完成这项工作。不确定其他 Windows 版本或其他语言的本地化。部分样本输出:

C:\Documents and Settings\colin>nbtstat -n

Local Area Connection: Node IpAddress: [192.168.1.100] Scope Id: []

            NetBIOS Local Name Table

C:\Documents and Settings\colin>nbtstat -n

本地连接:节点 IpAddress:[192.168.1.100] Scope Id:[]

            NetBIOS Local Name Table

etc.

等等。

回答by DonkeyKong

Option Explicit
Sub Main()

Dim wsh As Object
Dim strIPOutputFile As String, strSingleLine As String, strIP As String, strToFind As String
Dim intSourceFile As Integer, intLocation As Integer

    Set wsh = CreateObject("WScript.Shell")

    strIPOutputFile = "C:\Users\MeMeMeMe\Desktop\txtfile.txt"

'Save ipconfig info to file
    wsh.Run "%comspec% /c ipconfig/all> """ & strIPOutputFile & """

'Close any open text files
   Close

'Get the number of the next free text file
   intSourceFile = FreeFile

   Open strIPOutputFile For Input As intSourceFile

    strToFind = "IPv4 Address. . . . . . . . . . . :" 'This will probably depend on your file
   Do Until EOF(intSourceFile)
        Input #intSourceFile, strSingleLine
      If InStr(1, strSingleLine, strToFind) > 0 Then
        Exit Do
      End If
    Loop

    intLocation = Len(strToFind)
   strIP = Trim(Mid(strSingleLine,1 + intLocation,Len(strSingleLine) - intLocation))

    intLocation = Len(strIP)
    While Not IsNumeric(Mid(strIP,intLocation,1))
       strIP = Left(strIP, Len(strIP) - 1)
       intLocation = Len(strIP)
    Wend

    Close

   MsgBox strIP

End Sub

回答by RichO

Codeproject has a good article on how to do this with .net: http://www.codeproject.com/KB/cs/network.aspx

Codeproject 有一篇关于如何使用 .net 执行此操作的好文章:http: //www.codeproject.com/KB/cs/network.aspx

You could always create a console executable out of this, and call it from VBA.

您始终可以从中创建一个控制台可执行文件,并从 VBA 中调用它。

RO

反渗透