I Have Script to get IP Address based on PHP and WMI like this:
Get Active Adapter Network
function get_server_network_adapter() {
$pc = ".";
$obj = new COM ("winmgmts:\\\\".$pc."\oot\\cimv2");
$wmi_network_rec = $obj->ExecQuery("Select * from Win32_NetworkAdapter Where NetConnectionStatus = 2");
foreach ($wmi_network_rec as $wmi_call) {
$adapter = $wmi_call->Name;
return $adapter;
}
}
and Get IPAdress of Active Adapter
function get_server_ip()
{
$adapter = get_server_network_adapter();
$pc = ".";
$obj = new COM ("winmgmts:\\\\".$pc."\oot\\cimv2");
$wmi_server_ip = $obj->ExecQuery("Select * from Win32_NetworkAdapterConfiguration Where Description = '$adapter'");
foreach ($wmi_server_ip as $wmi_call) {
$ip = $wmi_call->IPAddress;
foreach ($ip as $key => $value) {
echo $value;
}
}
}
The Result of my code above is 192.168.1.103fe80::e9ad:9bb:e359:a122
However what I want is to only get the IPv4 like 192.168.1.103
Can someone help me? Thanks
Abstractedly from php
tag, IPAddress
property is simple an array in any used language. Read about it in MSDN article Win32_NetworkAdapterConfiguration class:
IPAddress
Data type: string array
Access type: Read-only
Qualifiers: MappingStrings
("Win32Registry|System\CurrentControlSet\Services|Parameters\Tcpip|IPAddress")Array of all of the IP addresses associated with the current network adapter. This property can contain either IPv6 addresses or IPv4 addresses. For more information, see IPv6 and IPv4 Support in WMI.
However (above your question topic), identifying a network adapter via Name
or Description
property does not seem to be a good idea. Use InterfaceIndex
property instead. Read Win32_NetworkAdapterConfiguration class as well as Win32_NetworkAdapter class MSDN articles:
InterfaceIndex
Data type: uint32
Access type: Read-onlyIndex value that uniquely identifies the local network interface. The value in this property is the same as the value in the
InterfaceIndex
property in the instance of Win32_IP4RouteTable that represents the network interface in the route table.