#PSTip Resolve IP Address or a host name using .NET Framework

Using the GetHostEntry static method of the  .NET Framework System.Net.Dns class it  is possible to resolve IP address or a host name:

[System.Net.Dns]::GetHostEntry('computer1')

HostName                   Aliases   AddressList
--------                   -------   -----------
computer1.jaapbrasser.com  {}        {fe80::99e1:800d:6c35:e406%10, 10.0.0.1}

If the IP address is what is required  then the following PowerShell 3.0 syntax can be used:

[System.Net.Dns]::GetHostEntry('localhost').AddressList.IPAddressToString

To filter only IPv4 addresses the following filter can be added:

[System.Net.Dns]::GetHostEntry('localhost').AddressList.IPAddressToString | Where-Object {$_ -match '\.'}

To filter only IPv6 addresses just change the operator from -match to -notmatch. For a full list of the available methods in this .NET class the following command can be used:

[System.Net.Dns] | Get-Member -MemberType method -Static

A full description of this .NET class can be found at MSDN:http://msdn.microsoft.com/en-us/library/b8hth2dy

Editor’s note:
The formal way to filter IPv4 address only would be by comparing against the AddressFamily property:

[System.Net.Dns]::GetHostEntry('localhost').AddressList |
Where-Object {$_.AddressFamily -eq 'InterNetwork'} |
ForEach-Object {$_.IPAddressToString}

For a complete list of AddressFamily values, see the AddressFamily Enumeration page on MSDN

About the author: Jaap Brasser

Jaap is a Senior System Engineer in the Financial Services industry. He focuses on Microsoft and related technologies and has a passion for PowerShell. In his spare time he maintains his Blog, Twitter feed, @Jaap_Brasser, and contributes on the Official Scripting Guys Forum and Windows PowerShell TechNet forums

Related Posts

%d bloggers like this: