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;


效果图:


阅读更多
换一批

没有更多推荐了,返回首页