2009-05-06 12 views
9

¿Cuál es la forma menos engorrosa (inclusión de módulo, longitud de código, etc.) de recuperar la dirección IP de la máquina (de la primera interfaz abierta)? Conozco algunas soluciones usando MSINET, pero creo que podemos hacerlo mejor. No responda¿Cómo recuperar la dirección IP de esta computadora?

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

porque no es tan gracioso ... o correcta. El escenario es una pregunta con un document ID feature Estoy intentando construir una respuesta para.

+0

pensé que la dirección IP puede ser parte de las variables de entorno y ser obtenido usando Environ ([índice o nombre]), pero por desgracia no es –

+0

Ver: [Realizar búsquedas de IP y resolver direcciones] (http : //www.mvps.org/access/api/api0067.htm) –

Respuesta

18

Aquí está un ejemplo adaptado de 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 

Requiere que tenga Microsoft WMI Scripting Library en las referencias del proyecto.

+0

¡Bien hecho! Muy compacto, aunque es un fragmento de código verdaderamente "solo de escritura" ... Estudiaré la versión de WMI durante los próximos 2 meses, solo para tener una idea de lo que se está haciendo aquí. Por cierto, bienvenidos a SO. – jpinto3912

+0

No hay magia profunda aquí en realidad. :) Agregué comentarios para explicar lo que se está haciendo. – Helen

+0

FYI, WMI significa Intstumentation de Windows Management; es un componente de Windows que proporciona una forma de realizar muchas tareas de administración de hardware, software y red. Acá algunos enlaces útiles: sésamo guión: lenguaje de consulta de WMI (éste es divertido :) http://www.microsoft.com/technet/scriptcenter/resources/begin/ss1206.mspx WMI Scripting Primer: http://www.microsoft.com/technet/scriptcenter/guide/sas_wmi_overview.mspx Referencia de WMI @ MSDN: http://msdn.microsoft.com/en-us/library/aa394582.aspx – Helen

1

Puede ejecutar el comando de shell ipconfig y analizar los resultados devueltos?

+0

Podríamos redirigir la salida de cmd a un txt ... pero intente con ipconfig en win2000, xp y vista y verá por qué es un gran desastre no no. – jpinto3912

+0

No estoy seguro de por qué es tan sucio? ¿Podrías elaborar? – sybreon

+0

El token requerido no siempre aparece en el mismo lugar, no rodeado por las mismas palabras.Un asesino final es que la configuración regional cambia la redacción que rodea al token del campo IP. Manejar esto, incluso con expresiones regulares, estaría lejos de ser trivial. – jpinto3912

2

Un par de ejemplos que encontré: -

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

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

EDITAR

Este es el código del primer enlace con una ligera modificación

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 
+0

hmmm .. Lo intentaré, skrink hasta que ya no pueda entender el código, y si todavía funciona, lo tienes . – jpinto3912

+0

El primer código de enlace es bueno (el segundo no puede ser, necesita un nombre de PC propio). Es compacto, no depende del exterior, y creo que la API no cambiará. Le pido que copie y pegue ese código aquí, guarde el aviso de copyright, pero modifiquemos el Sub para que sea una función sin args (lo que significa que siempre filtraremos 127.0.0.1) devolviendo la cadena. Lo marcaré correcto. Gracias, y bien hecho! – jpinto3912

+0

muchas gracias: hice la edición que solicitó. perdón por el formateo - stackoverflow no parece ser muy amigable para VBA ;-) –

0

nbtstat -n podría hacer el trabajo en XP de todos modos. No estoy seguro acerca de otras versiones de Windows o acerca de la localización en otros idiomas. Parcial resultado de ejemplo:

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

conexión de área local: Dirección IP de nodo: [192.168.1.100] Id Alcance: []

  NetBIOS Local Name Table 

etc.

+0

si bien sería posible volver a expresar el resultado para hacer frente a la localización, solo funciona si netbios api está presente ... hoy en día es cada vez más raro (debido a agujeros de seguridad del tamaño de jupiter) – jpinto3912

0
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 
Cuestiones relacionadas