Search Tools Links Login

Resolving IP to Hostname with PowerShell


Getting the hostname from an IP address (or vice versa) is no great magic, and can be done easily with PowerShell, by simply leveraging .Net to do the work.

We've all done something like this to get resolve an IP address:

[System.Net.Dns]::GetHostEntry("69.69.95.133").HostName

Or this to get an IP address from a hostname:

[System.Net.DNS]::GetHostAddresses("www.fortypoundhead.com").IPAddressToString

But did you ever notice that sea of red when you specify an invalid IP address or hostname? When you do that, you'll get a big,red error message similar to the following:

[System.Net.Dns]::gethostentry("128.254.95.254").HostName
Exception calling "GetHostEntry" with "1" argument(s): "No such host is known"
At line:1 char:1
+ [System.Net.Dns]::gethostentry("128.254.95.254").HostName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SocketException

I recently got asked how that nonsense could be avoided. Well, the answer is to simply encapsulate the process in a function that wraps up the .Net method to get the data back. It's pretty simple, and here is the code:

[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$IPAddress
)
# noise if we fail

$ErrorActionPreference = "silentlycontinue"
$Result = $null

# Pass the IP to .Net for name resolution.

$result = [System.Net.Dns]::gethostentry($IPAddress)

# process the results

If ($Result)
{
$MyResult = [string]$Result.HostName
}
Else
{
$MyResult = "unresolved"
}

# Send it to the output

$MyResult

Alternatively, you could also plug this directly into a standalone script. For example, lets say that you have a list of IP addresses in a file that you want to resolve to host names. No problem: # Get list from file, initialize empty array

$ListOfIPs=Get-content ".\hosts.txt"
$ResultList = @()

# roll through the list, resolving as we
# go with the .Net DNS resolver

foreach ($IP in $ListOfIPs)
{
# We don't want to see any errors as we go, right?

$ErrorActionPreference = "silentlycontinue"
$Result = $null

# status to user, just so they know that something
# is still happening, then pass the current IP
# to .Net for name resolution.

write-host "resolving $IP"
$result = [System.Net.Dns]::gethostentry($IP)


# Enter into the array, with the returned results.

If ($Result)
{
$ResultList += "$IP," + [string]$Result.HostName
}
Else
{
$ResultList += "$IP,unresolved"
}
}

# send it out to a file, and inform the user we are done

$ResultList | Out-File .\resolved.txt
write-host "name resolution complete"

Again, pretty straightforward.

First, it grabs the list of IP addresses from a file called hosts.txt. Next, the script runs through the list, resolving the IP addresses (if it can), storing the results in $ResultList. Finally, the output is sent to another file called resolved.txt

I hope this is useful to someone, and drop a note in the comments or in the forums if you have questions.

About this post

Posted: 2016-01-15
By: dwirch
Viewed: 31,734 times

Categories

Tip

Scripting

Powershell

PowerShell Code Cache

Attachments

No attachments for this post


Loading Comments ...

Comments

AnonymousCoward posted this comment on 2016-08-29:

Have all my upvotes. Reposting this to reddit. This was nearly impossible to find for servers still on powershell 2.0. Nice work

AnonymousCoward posted this comment on 2018-08-01:

Perfect! This was a complete solution! Why can't the folks who "try" to help with scripting actually test their scripts before posting to the world? Kudos to you!

dwirch posted this comment on 2018-08-01:

@Anonymous Coward on 2018-08-01 -

Good to know that you got some use out of this! Let me know if there is anything else I can help you with.

AnonymousCoward posted this comment on 2019-01-23:

I've been user a shorter version of this that seems to work just as well:

$Result = $null

changed to

$Result = "unresolved"

and the whole IF statement reduced to

$ResultList += "$IP," + [string]$Result.HostName

I found that if the IP didn't resolve it would leave $Result as it was (unresolved)

dwirch posted this comment on 2019-01-23:

Thanks for sharing!

AnonymousCoward posted this comment on 2020-06-03:

When writing a script think about error handling, it will save you time. My version is simple and short with error handling,  in this case I use try..catch. 

$ErrorActionPreference = "stop"
$IPAddress = gc "C:\temp\IPlist.txt"

foreach($ip in $IPAddress){

   try{
   
   Write-Host "Connecting to $IP" -Fore Cyan
   
   $IpTohost = [System.Net.Dns]::gethostentry($ip).HostName
   $IpTohost | Out-File c:\temp\IPtoHostname.txt -Append
   }
   catch{   
      $ip | Out-file "c:\temp\IpToHostLog.txt" -Append 
   }
}
   

 

dwirch posted this comment on 2020-06-03:

@AnonymousCoward - Thanks for sharing!

You must be logged in to make a comment.

ADODB.Connection error '800a0e79'

Operation is not allowed when the object is open.

/assets/inc/inc_footer.asp, line 37