首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 透過 NetBIOS 取得網卡 MAC 位址

     編輯:Delphi

應用場景

軟體授權綁定、機器唯一識別常需取得網卡實體位址 (MAC Address)。本文提供完整 Delphi 單元 (Nb.pas) 封裝 Windows NetBIOS API (Netbios),支援 32 位元環境,可列舉所有 LANA 編號並查詢各介面卡 MAC。

核心單元 Nb.pas 關鍵函數

  • NbLanaEnum:列舉系統所有 LANA 編號。
  • NbReset(LanaNum):重設指定 LANA (Win32 必須)。
  • NbGetMacAddr(LanaNum): String:傳回格式 XX:XX:XX:XX:XX:XX 的 MAC 字串。

主要程式碼結構 (Node.pas 摘要)

unit Nb;

interface
uses SysUtils, WinProcs, WinTypes;

const
  NCB_ENUM = $37; NCB_ADPSTAT = $33; NCB_RESET = $32;
  NRC_GOODRET = $00; MAXLANAS = 254; NBNAMESIZE = 16;

type
  TMacAddress = array[0..5] of Byte;
  TNCB = packed record ... end;  // NetBIOS Control Block
  TAdpStat = packed record
    ID: TMacAddress;  // MAC 位址在此
    ...
  end;
  TLana_Enum = packed record Length: Byte; Lana: array[0..MAXLANAS-1] of Byte; end;

function NetbiosCmd(var NCB: TNCB): Word;
function NbLanaEnum: TLana_Enum;
function NbReset(Lana: Byte): Word;
function NbGetMacAddr(LanaNum: Integer): String;

implementation
// ... 完整實作包含 Win32 CallNetbios、結構定義、錯誤碼常數 ...
// 關鍵:NbGetMacAddr 發送 NCB_ADPSTAT 命令,CallName='*', 解析 AdpStat.ID
end.

測試表單 Unit1.pas

unit Unit1;

interface
uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
     StdCtrls, Nb, ExtCtrls;

type
  TForm1 = class(TForm)
    Panel1: TPanel; Memo1: TMemo; Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  end;

implementation
{$R *.DFM}

procedure TForm1.FormCreate(Sender: TObject);
var
  LEnum: TLana_Enum; Ret: Word; I: Integer;
begin
  LEnum := NbLanaEnum;
  if LEnum.Length = 0 then
  begin
    Button1.Caption := Format('Enum Err: %.2X', [LEnum.Lana[0]]); Exit;
  end;
  for I := 0 to LEnum.Length - 1 do
  begin
    Ret := NbReset(LEnum.Lana[I]);
    if Ret <> NRC_GOODRET then
    begin
      Button1.Caption := Format('Reset %d Err: %.2X', [I, Ret]); Exit;
    end;
    Memo1.Lines.Add(Format('LANA %.2X = %s', [LEnum.Lana[I], NbGetMacAddr(I)]));
  end;
  Button1.Caption := 'Done';
end;

procedure TForm1.Button1Click(Sender: TObject);
begin Close; end;

end.

注意事項

  • 需將 Nb.pas 加入專案,或編譯為獨立單元。
  • Win9x/NT/2000/XP 皆可運作;Vista 以降 NetBIOS 可能需啟用相容性。
  • 若有多張網卡,會列出所有啟用介面的 MAC。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved