我希望使用一个唯一标识符来确定我的应用程序是否移动到了另一台计算机。MAC地址似乎适合这个目的。我使用的代码如下:
Procedure TForm4.GetMacAddress;
var item: TListItem;
objWMIService : OLEVariant;
colItems : OLEVariant;
colItem : OLEVariant;
oEnum : IEnumvariant;
iValue : LongWord;
wmiHost, root, wmiClass: string;
i: Int32;
function GetWMIObject(const objectName: String): IDispatch;
var
chEaten: Integer;
BindCtx: IBindCtx;//for access to a bind context
Moniker: IMoniker;//Enables you to use a moniker object
begin
OleCheck(CreateBindCtx(0, bindCtx));
OleCheck(MkParseDisplayName(BindCtx, StringToOleStr(objectName), chEaten, Moniker));//Converts a string into a moniker that identifies the object named by the string
OleCheck(Moniker.BindToObject(BindCtx, nil, IDispatch, Result));//Binds to the specified object
end;
begin
wmiHost := '.';
root := 'root\CIMV2';
wmiClass := 'Win32_NetworkAdapterConfiguration';
objWMIService := GetWMIObject(Format('winmgmts:\\%s\%s',[wmiHost,root]));
colItems := objWMIService.ExecQuery(Format('SELECT * FROM %s',[wmiClass]),'WQL',0);
oEnum := IUnknown(colItems._NewEnum) as IEnumVariant;
i := 0;
while oEnum.Next(1, colItem, iValue) = 0 do
begin
Item := View.Items.Add;
item.Caption := Copy (colItem.Caption, 2, 8);
Item.SubItems.Add (colItem.Description);
Item.SubItems.Add (colItem.ServiceName);
Item.SubItems.Add (VarToStrNil (colItem.MACAddress));
if (VarToStrNil(colItem.MACAddress) <> '')
then Item.SubItems.Add ('yes')
else Item.SubItems.Add ('no');
if colItem.IPEnabled
then Item.SubItems.Add ('yes')
else Item.SubItems.Add ('no');
Item.SubItems.Add (VarToStrNil (colItem.SettingID));
Item.SubItems.Add (IntToStr (colItem.InterfaceIndex));
end; // if
end; // GetMacAddress //
我的计算机只有一个网络端口,但是这段代码找到了18个与网络相关的端口/设备/其他。其中有四个MAC地址。我认为网络端口应该启用IP,因此只剩下两个(在图像中标记为MAC)。可以假设,在筛选出的端口中,索引最低的端口是硬件端口吗?
在上面的快照中,Realtek适配器是计算机中唯一的物理适配器。另一个适配器是VirtualBox虚拟适配器。TLama的答案确定了这两个适配器,但是否有办法找到唯一物理(Realtek)适配器的地址?
EJP指出MAC地址可以更改。这有点挫败了我的目的,但由于我正在寻找适合大多数情况的解决方案,所以我决定接受它。
TLama和TOndrej指出了几种解决方案。最终都无法毫无疑问地找到物理适配器。
TLama的优秀阅读列表显示,可能没有确定的方法来确定物理适配器。第一条提示中提到的文章显示如何基于一些简单的假设缩小适配器的数量。第三个提示中的文章显示如何选择连接到PCI总线的适配器,这实际上就是我想知道的。文章中提到了一些奇怪的异常情况,但我认为这将在大多数情况下提供答案。
感谢大家的贡献!