Programming/Delphi

맥 어드레스 알아내기

통통만두 2010. 7. 25. 10:53
반응형
uses NB30.pas

function GetMACAdress: string;
var
  NCB: PNCB;
  Adapter: PAdapterStatus;

  URetCode: PChar;
  RetCode: char;
  I: integer;
  Lenum: PlanaEnum;
  _SystemID: string;
  TMPSTR: string;
begin
  Result    := '';
  _SystemID := '';
  Getmem(NCB, SizeOf(TNCB));
  Fillchar(NCB^, SizeOf(TNCB), 0);

  Getmem(Lenum, SizeOf(TLanaEnum));
  Fillchar(Lenum^, SizeOf(TLanaEnum), 0);

  Getmem(Adapter, SizeOf(TAdapterStatus));
  Fillchar(Adapter^, SizeOf(TAdapterStatus), 0);

  Lenum.Length    := chr(0);
  NCB.ncb_command := chr(NCBENUM);
  NCB.ncb_buffer  := Pointer(Lenum);
  NCB.ncb_length  := SizeOf(Lenum);
  RetCode         := Netbios(NCB);

  i := 0;
  repeat
    Fillchar(NCB^, SizeOf(TNCB), 0);
    Ncb.ncb_command  := chr(NCBRESET);
    Ncb.ncb_lana_num := lenum.lana[I];
    RetCode          := Netbios(Ncb);

    Fillchar(NCB^, SizeOf(TNCB), 0);
    Ncb.ncb_command  := chr(NCBASTAT);
    Ncb.ncb_lana_num := lenum.lana[I];
    // Must be 16
    Ncb.ncb_callname := '*               ';

    Ncb.ncb_buffer := Pointer(Adapter);

    Ncb.ncb_length := SizeOf(TAdapterStatus);
    RetCode        := Netbios(Ncb);
    //---- calc _systemId from mac-address[2-5] XOR mac-address[1]...
    if (RetCode = chr(0)) or (RetCode = chr(6)) then
    begin
      _SystemId := IntToHex(Ord(Adapter.adapter_address[0]), 2) + '-' +
        IntToHex(Ord(Adapter.adapter_address[1]), 2) + '-' +
        IntToHex(Ord(Adapter.adapter_address[2]), 2) + '-' +
        IntToHex(Ord(Adapter.adapter_address[3]), 2) + '-' +
        IntToHex(Ord(Adapter.adapter_address[4]), 2) + '-' +
        IntToHex(Ord(Adapter.adapter_address[5]), 2);
    end;
    Inc(i);
  until (I >= Ord(Lenum.Length)) or (_SystemID <> '00-00-00-00-00-00');
  FreeMem(NCB);
  FreeMem(Adapter);
  FreeMem(Lenum);
  GetMacAdress := _SystemID;
end;



// 모든 맥어드레스 얻기
// uses 절에 추가되는 것은 JEDI API 
uses IpHlpApi, IpTypes;

function Tfrm_Main.GetAllMacAddress : String;
var
   NumInterfaces: Cardinal;
   AdapterInfo: array of TIpAdapterInfo;

   OutBufLen: ULONG;
   i: integer;
begin
   GetNumberOfInterfaces(NumInterfaces);
   SetLength(AdapterInfo, NumInterfaces);
   OutBufLen := NumInterfaces * SizeOf(TIpAdapterInfo);
   GetAdaptersInfo(@AdapterInfo[0], OutBufLen);
   Result := '';

   for i := 0 to NumInterfaces - 1 do begin
      if AdapterInfo[i].AddressLength = 0 then Continue;
      
      Result := '|' + Result + Format('%.2x:%.2x:%.2x:%.2x:%.2x:%.2x',
       [AdapterInfo[i].Address[0], AdapterInfo[i].Address[1],
        AdapterInfo[i].Address[2], AdapterInfo[i].Address[3],
        AdapterInfo[i].Address[4], AdapterInfo[i].Address[5]]);
   end;

   Delete(Result, 1, 1);
end;




반응형