#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:


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

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


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

Filed in: Columns, Tips and Tricks Tags: , , ,
© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: