1. 程式人生 > >delphi 獲取多網絡卡IP地址列表和Mac地址

delphi 獲取多網絡卡IP地址列表和Mac地址

1、宣告windows系統的sendarp函式

function sendarp(ipaddr: ulong; temp: dword; ulmacaddr: pointer; ulmacaddrleng: pointer): Dword; StdCall;External 'Iphlpapi.dll' Name 'SendARP';

2、usesWinSock;

3、獲取所有IP列表,適用於多網絡卡的情況
function GetLocalIpList(var IpList:TStringList):Integer;


type
  TaPInAddr = array[0..10] of PInAddr;
  PaPInAddr = ^TaPInAddr;


var
  HostName: array [0..MAX_PATH] of char;
  NameLen: Integer;
  WSData: TWSAData;
  lpHostEnt: PHostEnt;
  I: Integer;
  pptr: PaPInAddr;
begin
  Result := 0;
  if WSAStartup(MakeWord(2,0), WSData) <> 0 then Exit;
  try
  NameLen := sizeof(HostName);
  fillchar(HostName, NameLen, 0);
  NameLen := GetHostName(HostName, NameLen);
  if NameLen = SOCKET_ERROR then Exit;


  lpHostEnt := GetHostByName(HostName);
  if lpHostEnt = Nil then Exit;


  I := 0;
  pPtr := PaPInAddr(lpHostEnt^.h_addr_list);
  IpList.Clear;
  while pPtr^[I] <> nil do
  begin
    IpList.Add(inet_ntoa(pptr^[I]^));
    Inc(I);
  end;


  Result := IpList.Count;
finally
  WSACleanup;
end;


end;

4、根據IP獲取Mac
function GetMACByIP(const Ip:string):string;
var
  MyIp:ulong;
  MyMac:array[0..5] of byte;
  MyMacLength:ulong;
  ErrCode:integer;
begin
  Myip:=inet_addr(PChar(Ip));
  MyMacLength:=Length(MyMac);
  ErrCode:=SendArp(MyIp,0,@MyMac,@MyMacLength);
  if ErrCode = 0 then
    Result := Format('%2.2x-%2.2x-%2.2x-%2.2x-%2.2x-%2.2x',[MyMac[0],MyMac[1],MyMac[2],MyMac[3],MyMac[4],MyMac[5]])
  else
    Result := '';
end;

5、取出第一個Mac地址
function GetFirstMac: string;
var
  IpList: TStringList;
begin
  result := '';


  IpList := TStringList.Create;
  try
    GetLocalIpList(IpList);
    if IpList.Count > 0 then
      result := GetMACByIP(IpList[0]);
  finally
    FreeAndNil(IpList);
  end;
end;

效果圖: