Get Physical Network Adapters

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
DataLife
Posts: 447
Joined: 29 Sep 2013, 19:52

Get Physical Network Adapters

Post by DataLife » 31 Jan 2023, 17:10

This code will get a list of Physical Network Adapters using powershell but it takes about 4 seconds.

Anyone know of a way to get a list of Physical Network Adapters faster?

Code: Select all

SavedClipboard := clipboard
RunWait PowerShell.exe Get-NetAdapter -Physical """*""" | clip,,hide
for x,y in strsplit(clipboard,"`r","`n")
 {
  if InStr(y, "up") or InStr(y, "disconnected")
   {
    TempVar := trim(substr(y,1,26)," ")
    PhysicalAdapters = %PhysicalAdapters%`n%TempVar%
   }
 }	
Clipboard := SavedClipboard
MsgBox % PhysicalAdapters
Check out my scripts. (MyIpChanger) (ClipBoard Manager) (SavePictureAs)
All my scripts are tested on Windows 10, AutoHotkey 32 bit Ansi unless otherwise stated.

gmoises
Posts: 74
Joined: 18 Nov 2017, 16:43

Re: Get Physical Network Adapters

Post by gmoises » 31 Jan 2023, 17:47

It can be done using WMI.
I made this Script that you can adapt easily
At the end there are 2 lists with all the properties of the objects

Code: Select all

/*
	Get the data from the physical network adapters,
	skip the virtual ones:
	skip Bluetooth, TeamViewer, Oracle, ZeroTier, vEthernet.
	For each adapter, get the IP, if it doesn't have an IP,
	it means it's not connected.
*/

#Requires AutoHotkey v1.1.36+
For Ix, NIC in Sacar_NICs()
{	For Que, Dato in NIC
		Txt .= Que . Tabs(Que) . Dato . "`n"
	MsgBox % Txt
	Txt := ""
}


Sacar_NICs() {
	ColNICs := []
	strComputer := "."
	objWMIService := ComObjGet("winmgmts:{impersonationLevel=impersonate}!\\" . strComputer . "\root\cimv2")
	colItems := objWMIService.ExecQuery("Select * from Win32_NetworkAdapter")._NewEnum

	While colItems[objItem]
		If objItem.PhysicalAdapter and !InStr(objItem.NetConnectionID, "Bluetooth")
			If !InStr(objItem.Manufacturer, "TeamViewer") and !InStr(objItem.Manufacturer, "Oracle")
				If !InStr(objItem.NetConnectionID, "ZeroTier") and !InStr(objItem.NetConnectionID, "vEthernet")
				{	CadaNIC := []
					MAC1 := objItem.MACAddress
					CadaNIC["Description"]			:= objItem.Description
					CadaNIC["NetConnectionID"]		:= objItem.NetConnectionID
					CadaNIC["Manufacturer"]			:= objItem.Manufacturer
					CadaNIC["ProductName"]			:= objItem.ProductName
					CadaNIC["AdapterType"]			:= objItem.AdapterType
					CadaNIC["MACAddress"]			:= objItem.MACAddress
					CadaNIC["NetConnectionStatus"]	:= objItem.NetConnectionStatus
					CadaNIC["Speed"]				:= objItem.Speed
					CadaNIC["NetEnabled"]			:= objItem.NetEnabled
					colItems2 := objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration")._NewEnum
					While colItems2[objItem2]
					{	Mac2 := objItem2.MACAddress
						If (Mac1 = Mac2)
							For Cada, Dato in objItem2.IPAddress
							{	++Ix
								CadaNIC["IPAddress-" . Ix]	:= Cada
							}
							Ix := 0
					}
					colItems2 := objItem2 := ""
					ColNICs.Push(CadaNIC)
				}
	Return, ColNICs
}

Tabs(ByRef Txt) {
	Largo := StrLen(Txt)
	If Largo > 16
		Return, "`t"
	If Largo > 8
		Return, "`t`t"
	Return, "`t`t`t"
}

/*
	[Dynamic, Provider("CIMWin32"), UUID("{8502C4C0-5FBB-11D2-AAC1-006008C78BC7}"), AMENDMENT]
	class Win32_NetworkAdapter : CIM_NetworkAdapter
	{
	  string   AdapterType;
	  uint16   AdapterTypeID;
	  boolean  AutoSense;
	  uint16   Availability;
	  string   Caption;
	  uint32   ConfigManagerErrorCode;
	  boolean  ConfigManagerUserConfig;
	  string   CreationClassName;
	  string   Description;
	  string   DeviceID;
	  boolean  ErrorCleared;
	  string   ErrorDescription;
	  string   GUID;
	  uint32   Index;
	  datetime InstallDate;
	  boolean  Installed;
	  uint32   InterfaceIndex;
	  uint32   LastErrorCode;
	  string   MACAddress;
	  string   Manufacturer;
	  uint32   MaxNumberControlled;
	  uint64   MaxSpeed;
	  string   Name;
	  string   NetConnectionID;
	  uint16   NetConnectionStatus;
	  boolean  NetEnabled;
	  string   NetworkAddresses[];
	  string   PermanentAddress;
	  boolean  PhysicalAdapter;
	  string   PNPDeviceID;
	  uint16   PowerManagementCapabilities[];
	  boolean  PowerManagementSupported;
	  string   ProductName;
	  string   ServiceName;
	  uint64   Speed;
	  string   Status;
	  uint16   StatusInfo;
	  string   SystemCreationClassName;
	  string   SystemName;
	  datetime TimeOfLastReset;
	};
*/

/*
	[Dynamic, Provider("CIMWin32"), UUID("{8502C515-5FBB-11D2-AAC1-006008C78BC7}"), AMENDMENT]
	class Win32_NetworkAdapterConfiguration : CIM_Setting
	{
	  string   Caption;
	  string   Description;
	  string   SettingID;
	  boolean  ArpAlwaysSourceRoute;
	  boolean  ArpUseEtherSNAP;
	  string   DatabasePath;
	  boolean  DeadGWDetectEnabled;
	  string   DefaultIPGateway[];
	  uint8    DefaultTOS;
	  uint8    DefaultTTL;
	  boolean  DHCPEnabled;
	  datetime DHCPLeaseExpires;
	  datetime DHCPLeaseObtained;
	  string   DHCPServer;
	  string   DNSDomain;
	  string   DNSDomainSuffixSearchOrder[];
	  boolean  DNSEnabledForWINSResolution;
	  string   DNSHostName;
	  string   DNSServerSearchOrder[];
	  boolean  DomainDNSRegistrationEnabled;
	  uint32   ForwardBufferMemory;
	  boolean  FullDNSRegistrationEnabled;
	  uint16   GatewayCostMetric[];
	  uint8    IGMPLevel;
	  uint32   Index;
	  uint32   InterfaceIndex;
	  string   IPAddress[];
	  uint32   IPConnectionMetric;
	  boolean  IPEnabled;
	  boolean  IPFilterSecurityEnabled;
	  boolean  IPPortSecurityEnabled;
	  string   IPSecPermitIPProtocols[];
	  string   IPSecPermitTCPPorts[];
	  string   IPSecPermitUDPPorts[];
	  string   IPSubnet[];
	  boolean  IPUseZeroBroadcast;
	  string   IPXAddress;
	  boolean  IPXEnabled;
	  uint32   IPXFrameType[];
	  uint32   IPXMediaType;
	  string   IPXNetworkNumber[];
	  string   IPXVirtualNetNumber;
	  uint32   KeepAliveInterval;
	  uint32   KeepAliveTime;
	  string   MACAddress;
	  uint32   MTU;
	  uint32   NumForwardPackets;
	  boolean  PMTUBHDetectEnabled;
	  boolean  PMTUDiscoveryEnabled;
	  string   ServiceName;
	  uint32   TcpipNetbiosOptions;
	  uint32   TcpMaxConnectRetransmissions;
	  uint32   TcpMaxDataRetransmissions;
	  uint32   TcpNumConnections;
	  boolean  TcpUseRFC1122UrgentPointer;
	  uint16   TcpWindowSize;
	  boolean  WINSEnableLMHostsLookup;
	  string   WINSHostLookupFile;
	  string   WINSPrimaryServer;
	  string   WINSScopeID;
	  string   WINSSecondaryServer;
	};
*/


XMCQCX
Posts: 231
Joined: 14 Oct 2020, 23:44

Re: Get Physical Network Adapters

Post by XMCQCX » 01 Feb 2023, 00:04

GetAdaptersInfo() by jNizM, Requires AutoHotkey v2.0
https://github.com/jNizM/ahk-scripts-v2

malcev
Posts: 1769
Joined: 12 Aug 2014, 12:37

Re: Get Physical Network Adapters

Post by malcev » 01 Feb 2023, 00:48

gmoises, Win32_NetworkAdapter class is deprecated therefore Your wmi code shows virtual adapters too.
https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-networkadapter
XMCQCX, GetAdaptersInfo is deprecated too.
https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersinfo
Need something like this:

Code: Select all

if (DllCall("iphlpapi.dll\GetAdaptersAddresses", "uint", AF_UNSPEC := 0, "uint", 0, "ptr", 0, "ptr", 0, "uint*", size) = 111)   ; ERROR_BUFFER_OVERFLOW
{
   VarSetCapacity(buf, size, 0)
   if !DllCall("iphlpapi.dll\GetAdaptersAddresses", "uint", AF_UNSPEC := 0, "uint", 0, "ptr", 0, "ptr", &buf, "uint*", size)
   {
      addr := &buf
      while (addr)
      {
         msgbox % FriendlyName := StrGet(NumGet(addr + 8, A_PtrSize * 8, "ptr"), "UTF-16")
         addr := NumGet(addr + 8, "ptr")   ; *Next
      }
   }
}
But winapi doesnot have function to distinguish physical from virtual, therefore We can use wmi, like this:

Code: Select all

objWMIService := ComObjGet("winmgmts:\\.\root\StandardCimv2")
colItems := objWMIService.ExecQuery("SELECT * FROM MSFT_NetAdapter where ConnectorPresent=1")._NewEnum
while colItems[objItem]
   msgbox % objItem.Name

User avatar
DataLife
Posts: 447
Joined: 29 Sep 2013, 19:52

Re: Get Physical Network Adapters

Post by DataLife » 01 Feb 2023, 08:19

malcev wrote:
01 Feb 2023, 00:48
But winapi doesnot have function to distinguish physical from virtual, therefore We can use wmi, like this:

Code: Select all

objWMIService := ComObjGet("winmgmts:\\.\root\StandardCimv2")
colItems := objWMIService.ExecQuery("SELECT * FROM MSFT_NetAdapter where ConnectorPresent=1")._NewEnum
while colItems[objItem]
   msgbox % objItem.Name
Thanks, exactly what I need
Check out my scripts. (MyIpChanger) (ClipBoard Manager) (SavePictureAs)
All my scripts are tested on Windows 10, AutoHotkey 32 bit Ansi unless otherwise stated.

User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: Get Physical Network Adapters

Post by jNizM » 01 Feb 2023, 09:24

malcev wrote:
01 Feb 2023, 00:48
GetAdaptersInfo is deprecated too.
Will write a v2 function for this :thumbup:
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile

dedabrane
Posts: 1
Joined: 13 Sep 2023, 01:04

Re: Get Physical Network Adapters

Post by dedabrane » 13 Sep 2023, 07:35

gmoises wrote:
31 Jan 2023, 17:47
It can be done using WMI.
I made this Script that you can adapt easily
At the end there are 2 lists with all the properties of the objects

Code: Select all

/*
	Get the data from the physical network adapters,
	skip the virtual ones:
	skip Bluetooth, TeamViewer, Oracle, ZeroTier, vEthernet.
	For each adapter, get the IP, if it doesn't have an IP,
	it means it's not connected.
*/

#Requires AutoHotkey v1.1.36+
For Ix, NIC in Sacar_NICs()
{	For Que, Dato in NIC
		Txt .= Que . Tabs(Que) . Dato . "`n"
	MsgBox % Txt
	Txt := ""
}


Sacar_NICs() {
	ColNICs := []
	strComputer := "."
	objWMIService := ComObjGet("winmgmts:{impersonationLevel=impersonate}!\\" . strComputer . "\root\cimv2")
	colItems := objWMIService.ExecQuery("Select * from Win32_NetworkAdapter")._NewEnum

	While colItems[objItem]
		If objItem.PhysicalAdapter and !InStr(objItem.NetConnectionID, "Bluetooth")
			If !InStr(objItem.Manufacturer, "TeamViewer") and !InStr(objItem.Manufacturer, "Oracle")
				If !InStr(objItem.NetConnectionID, "ZeroTier") and !InStr(objItem.NetConnectionID, "vEthernet")
				{	CadaNIC := []
					MAC1 := objItem.MACAddress
					CadaNIC["Description"]			:= objItem.Description
					CadaNIC["NetConnectionID"]		:= objItem.NetConnectionID
					CadaNIC["Manufacturer"]			:= objItem.Manufacturer
					CadaNIC["ProductName"]			:= objItem.ProductName
					CadaNIC["AdapterType"]			:= objItem.AdapterType
					CadaNIC["MACAddress"]			:= objItem.MACAddress
					CadaNIC["NetConnectionStatus"]	:= objItem.NetConnectionStatus
					CadaNIC["Speed"]				:= objItem.Speed
					CadaNIC["NetEnabled"]			:= objItem.NetEnabled
					colItems2 := objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration")._NewEnum
					While colItems2[objItem2]
					{	Mac2 := objItem2.MACAddress
						If (Mac1 = Mac2)
							For Cada, Dato in objItem2.IPAddress
							{	++Ix
								CadaNIC["IPAddress-" . Ix]	:= Cada
							}
							Ix := 0
					}
					colItems2 := objItem2 := ""
					ColNICs.Push(CadaNIC)
				}
	Return, ColNICs
}

Tabs(ByRef Txt) {
	Largo := StrLen(Txt)
	If Largo > 16
		Return, "`t"
	If Largo > 8
		Return, "`t`t"
	Return, "`t`t`t"
}

/*
	[Dynamic, Provider("CIMWin32"), UUID("{8502C4C0-5FBB-11D2-AAC1-006008C78BC7}"), AMENDMENT]
	class Win32_NetworkAdapter : CIM_NetworkAdapter
	{
	  string   AdapterType;
	  uint16   AdapterTypeID;
	  boolean  AutoSense;
	  uint16   Availability;
	  string   Caption;
	  uint32   ConfigManagerErrorCode;
	  boolean  ConfigManagerUserConfig;
	  string   CreationClassName;
	  string   Description;
	  string   DeviceID;
	  boolean  ErrorCleared;
	  string   ErrorDescription;
	  string   GUID;
	  uint32   Index;
	  datetime InstallDate;
	  boolean  Installed;
	  uint32   InterfaceIndex;
	  uint32   LastErrorCode;
	  string   MACAddress;
	  string   Manufacturer;
	  uint32   MaxNumberControlled;
	  uint64   MaxSpeed;
	  string   Name;
	  string   NetConnectionID;
	  uint16   NetConnectionStatus;
	  boolean  NetEnabled;
	  string   NetworkAddresses[];
	  string   PermanentAddress;
	  boolean  PhysicalAdapter;
	  string   PNPDeviceID;
	  uint16   PowerManagementCapabilities[];
	  boolean  PowerManagementSupported;
	  string   ProductName;
	  string   ServiceName;
	  uint64   Speed;
	  string   Status;
	  uint16   StatusInfo;
	  string   SystemCreationClassName;
	  string   SystemName;
	  datetime TimeOfLastReset;
	};
*/

/*
	[Dynamic, Provider("CIMWin32"), UUID("{8502C515-5FBB-11D2-AAC1-006008C78BC7}"), AMENDMENT]
	class Win32_NetworkAdapterConfiguration : CIM_Setting
	{
	  string   Caption;
	  string   Description;
	  string   SettingID;
	  boolean  ArpAlwaysSourceRoute;
	  boolean  ArpUseEtherSNAP;
	  string   DatabasePath;
	  boolean  DeadGWDetectEnabled;
	  string   DefaultIPGateway[];
	  uint8    DefaultTOS;
	  uint8    DefaultTTL;
	  boolean  DHCPEnabled;
	  datetime DHCPLeaseExpires;
	  datetime DHCPLeaseObtained;
	  string   DHCPServer;
	  string   DNSDomain;
	  string   DNSDomainSuffixSearchOrder[];
	  boolean  DNSEnabledForWINSResolution;
	  string   DNSHostName;
	  string   DNSServerSearchOrder[];
	  boolean  DomainDNSRegistrationEnabled;
	  uint32   ForwardBufferMemory;
	  boolean  FullDNSRegistrationEnabled;
	  uint16   GatewayCostMetric[];
	  uint8    IGMPLevel;
	  uint32   Index;
	  uint32   InterfaceIndex;
	  string   IPAddress[];
	  uint32   IPConnectionMetric;
	  boolean  IPEnabled;
	  boolean  IPFilterSecurityEnabled;
	  boolean  IPPortSecurityEnabled;
	  string   IPSecPermitIPProtocols[];
	  string   IPSecPermitTCPPorts[];
	  string   IPSecPermitUDPPorts[];
	  string   IPSubnet[];
	  boolean  IPUseZeroBroadcast;
	  string   IPXAddress;
	  boolean  IPXEnabled;
	  uint32   IPXFrameType[];
	  uint32   IPXMediaType;
	  string   IPXNetworkNumber[];
	  string   IPXVirtualNetNumber;
	  uint32   KeepAliveInterval;
	  uint32   KeepAliveTime;
	  string   MACAddress;
	  uint32   MTU;
	  uint32   NumForwardPackets;
	  boolean  PMTUBHDetectEnabled;
	  boolean  PMTUDiscoveryEnabled;
	  string   ServiceName;
	  uint32   TcpipNetbiosOptions;
	  uint32   TcpMaxConnectRetransmissions;
	  uint32   TcpMaxDataRetransmissions;
	  uint32   TcpNumConnections;
	  boolean  TcpUseRFC1122UrgentPointer;
	  uint16   TcpWindowSize;
	  boolean  WINSEnableLMHostsLookup;
	  string   WINSHostLookupFile;
	  string   WINSPrimaryServer;
	  string   WINSScopeID;
	  string   WINSSecondaryServer;
	};
*/

Hello everyone.
I'm a beginner in programming but I'm trying to do my best..
This script is really useful for the work I'm trying to do, but I need some help.
I need to get some additional info of the network adapters like subnet mask and gateway.
I know this info is available in the Win32_NetworkAdapterConfiguration class, but I don't know how to edit the script to get this additional info.
Regarding the Ip address, I need only IPv4 and I managed to get this by adding "if (!InStr(Cada, ":"))" to avid showing IPv6.
One more thing I would need is to put all of the info into variables so I can use it further in the script.

So if someone is willing to help me, I would appreciate it a lot!

Thanks!

Post Reply

Return to “Ask for Help (v1)”