Page 1 of 1

Get MAC Adress from IP (Windows only)

Posted: Fri Dec 07, 2007 3:07 pm
by ABBKlaus
tested with PB4.10 on Windows XP / Vista Home Basic (32-Bit)

Code: Select all

EnableExplicit

InitNetwork()

Procedure.l GetNetworkComputerIP(computer$) ; returns ip adress of hostname/IP$
  ; Originally posted by Hi-Toro
  ; Posted: Sun Feb 16, 2003 8:27 pm
  ; http://purebasicforums.com/english/viewtopic.php?t=5151
  ; modified on 1.3.2005 by ABBKlaus
  ; modified on 8.12.2007 by ABBKlaus (unicode compatible)
  Protected *Buffer,*host.HOSTENT,ip.l
  
  If computer$ 
    *Buffer=AllocateMemory(MemoryStringLength(@computer$)+1)
    If *Buffer
      PokeS(*Buffer,computer$,-1,#PB_Ascii)
      *host = gethostbyname_(*Buffer) ; Get host information for named computer...
      If *host
        ip = PeekL(PeekL(*host\h_addr_list))
      EndIf 
      FreeMemory(*Buffer)
    EndIf 
  EndIf
  
  ProcedureReturn ip
EndProcedure

Procedure.s MacToString(*membuffer) ; returns MAC adress in string format
  Protected MAC.s,i.l
  
  MAC = ""
  For i=0 To 5
    MAC+RSet(Hex(PeekB(*membuffer+i)&$FF),2,"0")
    If i<5
      MAC+":"
    EndIf
  Next
  
  ProcedureReturn MAC
EndProcedure

Procedure.s GetMacFromIP(IP$) ; returns MAC adress from hostname or IP
  ;ABBKlaus on 7.12.2007
  ;http://msdn.microsoft.com/library/en-us/iphlp/iphlp/sendarp.asp
  Protected ip.l,thisip.l,maclen.l,*buffer,mac.s=""
  
  ip=GetNetworkComputerIP(IP$)
  thisip=GetNetworkComputerIP(Hostname())
  
  maclen=6
  *buffer=AllocateMemory(8)
  If *buffer
    If SendARP_(ip,thisip,*buffer,@maclen)=#NO_ERROR
      mac=MacToString(*buffer)
    Else
      Debug "SendARP failed"
    EndIf
    FreeMemory(*buffer)
  EndIf
  
  ProcedureReturn mac
EndProcedure

Debug GetMacFromIP("192.168.1.110") ; Fill in the desired Computername
Debug GetMacFromIP("klaus-core2") ; Fill in the desired Computername

Posted: Sat Dec 08, 2007 4:31 am
by SFSxOI
Does this work on Vista? I get ARP Failed.

Posted: Sat Dec 08, 2007 5:38 am
by rsts
Very nice - works fine here under Vista.

Good tip.

cheers

Posted: Sat Dec 08, 2007 6:45 am
by Hi-Toro
Nice one, Klaus, fine on XP here.

SFSxOI, are you changing the IP address passed to the function?

Code: Select all

Debug GetMacFromIP("klaus-core2") ' Insert own IP/PC name here!

Posted: Sat Dec 08, 2007 12:51 pm
by ABBKlaus
should work on vista, and now in unicode mode too :wink:

Posted: Sat Dec 08, 2007 2:51 pm
by Pantcho!!
Thanks this is very handy indeed.

Posted: Sat Dec 08, 2007 7:36 pm
by SFSxOI
got it working now, was a stupid permission thing.

Nice job. Thank You :)

Hi-Toro wrote:Nice one, Klaus, fine on XP here.

SFSxOI, are you changing the IP address passed to the function?

Code: Select all

Debug GetMacFromIP("klaus-core2") ' Insert own IP/PC name here!