Table of Contents
Using Resolve-DnsName Cmdlet
To retrieve the hostname from the given IP address in PowerShell, use the Resolve-DnsName cmdlet with -Type and PTR parameters.
|
1 2 3 |
Resolve-DnsName -Type PTR -Name 8.8.8.8 | Select-Object -ExpandProperty NameHost |
|
1 2 3 |
dns.google |
In this example, the Resolve-DnsName cmdlet resolves the IP addresses to DNS names (hostnames). The -Type parameter is used to specify that the query should be for a PTR record (a PTR record is a type of Domain Name System record that maps an IP address to a hostname), and the -Name parameter specified the IP address we want to resolve.
The command then pipes the output to the Select-Object cmdlet to expand the NameHost property, which contains the hostname corresponding to the IP address. The output is then piped to the Select-Object cmdlet to expand the NameHost property, which contains the hostname corresponding to the IP address.
Replace the
8.8.8.8with the IP address you want to resolve.
Using nslookup Command
Use the nslookup to get hostname from IP address in PowerShell.
|
1 2 3 4 |
$ipAddress = "213.133.127.245" nslookup $ipAddress | Select-String -Pattern 'Name:' |
|
1 2 3 |
Name: kronos.alteregomedia.org |
This code used the nslookup command to request the DNS server for the hostname associated with the IP address 213.133.127.245. The nslookup command output is piped to the Select-String cmdlet, which searches for lines containing the Name:, which includes the hostname information.
Further reading:
Using [System.Net.Dns]::GetHostByAddress Method
Use the [System.Net.Dns]::GetHostByAddress method to get hostname from IP address in PowerShell.
|
1 2 3 4 5 6 |
$ipAddress = "8.8.8.8" $hostEntry = [System.Net.Dns]::GetHostByAddress($ipAddress) $hostname = $hostEntry.HostName Write-Host "The hostname associated with IP address $ipAddress is $hostname" |
|
1 2 3 |
The hostname associated with IP address 8.8.8.8 is dns.google |
We can observe the above code retrieved the hostname of a given IP address. In this example, the $ipAddress variable contained the IP address we wanted to resolve. The [System.Net.Dns]::GetHostByAddress method used this $ipAddress variable as an input and returned the System.Net.IPHostEntry object that contains various details about the host. Once this object is returned, the .HostName property of the IPHostEntry object extracts the hostname.
That’s all about how to get hostname from IP address in PowerShell.