Команда resolve ip в windows

Бывает так, что у нас есть список имен и нужно разрешить их в IP адреса. Или наоборот. Вот удобный способ сделать это автоматически, используя Powershell

Допустим вы хотите разрешить имя в IP адрес или наоборот. Для этого в командной строке вы обычно пишите следующее:

И получаете такой вывод:

Server:  dns.google
Address:  8.8.8.8

Non-authoritative answer:
Name:    danshin.ms
Addresses:  185.199.108.153
          188.199.109.153
          185.199.110.153
          185.199.111.153

В Powershell это можно сделать так:

[system.net.dns]::resolve("danshin.ms")

В этом случае Вы получите такой вывод.

HostName   Aliases AddressList
--------   ------- -----------
danshin.ms {}      {185.199.108.153, 188.199.109.153, 185.199.110.153, 185.199.111.153}

Что делать, если адресов больше одного, например целый список адресов? В этом случае помещаем их в файл, например ip.txt.

danshin.ms
microsoft.com
google.com
facebook.com
cooking.danshin.ms

Далее делам так:

Помещаем содержимое файла в переменную powershell

Затем пишем цикл foreach:

foreach ($address in $ip) {
  [system.net.dns]::resolve($address)
}

В этом случае мы получим вывод следующего вида:

HostName                   Aliases              AddressList                                                            
--------                   -------              -----------                                                            
danshin.ms                 {}                   {185.199.108.153, 188.199.109.153, 185.199.110.153, 185.199.111.153}   
microsoft.com              {}                   {104.215.148.63, 40.76.4.15, 40.112.72.205, 40.113.200.201...}         
google.com                 {}                   {173.194.222.138, 173.194.222.113, 173.194.222.102, 173.194.222.139...}
facebook.com               {}                   {157.240.205.35}                                                       
mdanshin-cooking.github.io {cooking.danshin.ms} {185.199.108.153, 185.199.111.153, 185.199.110.153, 185.199.109.153} 

Если адресов будем много, то работа цикла foreach может занять значительно время. И чтобы выидеть прогресс давайте выведем его на экран. Для этого введём две дополнительные переменные

$count = $ip.Count
$current = 0

Затем выведем прогресс через Write-Progress. И вот, что у нас получилось:

$ip = Get-Content ip.txt

$count = $ip.Count
$current = 0

foreach ($address in $ip) {
  Write-Progress "Left to process $current addresses of $count" `
    -PercentComplete ( ( $current / $count ) * 100 )

  [system.net.dns]::resolve($address)
   
  $current++
}

И в заключении, чтобы иметь возможность форматировать получаемую таблицу, давайте результат работы цикла поместим в переменную и выведем его через Format-Table.

$ip = Get-Content ip.txt

$count = $ip.Count
$current = 0

$table = foreach ($address in $ip) {
  Write-Progress "Left to process $current addresses of $count" `
    -PercentComplete ( ( $current / $count ) * 100 )

  [system.net.dns]::resolve($address)
   
  $current++
}

$table | Format-Table

В таком виде будет удобно разрешать как IP в адреса так и наоборот.

Заходите в группу Telegram

Если есть вопросы или хотите пообщаться, то заходите в мою группу Telegram.

  1. Use the Resolve-DnsName Cmdlet to Resolve IP Address From Hostname With PowerShell

  2. Use the Dns.GetHostAddresses Method to Resolve IP Address From Hostname With PowerShell

How to Resolve IP Address From Hostname With PowerShell

A hostname, such as www.example.com, identifies a website or host on the internet. IP addresses are assigned to host names.

Sometimes you may need to get an IP address from the hostname or vice-versa. It can be easily done with the help of PowerShell.

This tutorial will teach you to resolve the IP address from hostname or vice-versa using PowerShell.

Use the Resolve-DnsName Cmdlet to Resolve IP Address From Hostname With PowerShell

The Resolve-DnsName cmdlet performs a DNS name query resolution for the specified name.

The following command resolves a hostname delftstack.com.

Resolve-DnsName delftstack.com

Output:

Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------
delftstack.com                                 A      60    Answer     3.6.118.31
delftstack.com                                 A      60    Answer     3.6.18.84

As you can see, it prints other information along with the IP address. To get only IP addresses, use the following command.

(Resolve-DnsName delftstack.com).IPAddress

Output:

To resolve a hostname from the IP address, you can specify an IP address to the command.

Resolve-DnsName 3.6.118.31

Output:

Name                           Type   TTL   Section    NameHost
----                           ----   ---   -------    --------
31.118.6.3.in-addr.arpa        PTR    300   Answer     ec2-3-6-118-31.ap-south-1.compute.amazonaws.com

Use the Dns.GetHostAddresses Method to Resolve IP Address From Hostname With PowerShell

The GetHostAddresses method of Dns Class displays the IP addresses of the specified host.

The following example returns the IP addresses of the host delftstack.com.

[System.Net.Dns]::GetHostAddresses('delftstack.com')

Output:

Address            : 1410467331
AddressFamily      : InterNetwork
ScopeId            :
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 3.6.18.84

Address            : 527828483
AddressFamily      : InterNetwork
ScopeId            :
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 3.6.118.31

It displays additional information like Address, AddressFamily, ScopeID, and others. To print only IP addresses, run the command below.

[System.Net.Dns]::GetHostAddresses('delftstack.com').IPAddressToString

Output:

The GetHostEntry method resolves a hostname from the IP address.

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

Output:

HostName                                        Aliases AddressList
--------                                        ------- -----------
ec2-3-6-118-31.ap-south-1.compute.amazonaws.com {}      {3.6.118.31}

We hope this tutorial gave you an idea to resolve an IP address from the hostname or vice-versa in PowerShell.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

In this article, we find out how to use PowerShell to read a list of IP addresses from a text file and resolve them to hostnames and then export to a CSV file for further reviewing.

A lot of systems like Windows Event logs, Firewall logs or IIS logs etc will store the connection information with IP addresses. Barely looking at the IP address may not give a good idea of what systems are connecting and resolving them to hostnames is much easier to process the data. The script that we are going to discuss will read a list of IP addresses from a text file, resolves them to hostnames, and finally exports them to CSV file.

We are going to use [System.Net.DNS] DotNet class for this purpose. The GetHostbyAddress() method available in this class will help us in resolving names to IP addresses.

Code

[CmdletBinding()]
param(
    [Parameter(Mandatory=$True)]
    [string[]]$IPAddress,
    [switch]$ExportToCSV
)

$outarr = @()
foreach($IP in $IPAddress) {
    $result = $null
    try {
        $Name = ([System.Net.DNS]::GetHostByAddress($IP)).HostName
        $result = "Success"

    } catch {
        $result = "Failed"
        $Name="NA"
    }

    $outarr += New-Object -TypeName PSObject -Property @{
        IPAddress = $IP
        Name = $Name
        Status = $result
    } | Select-Object IPAddress, Name, Status
}

if($ExportToCSV) {
    $outarr | export-csv -Path "c:\temp\iptoname.csv" -NoTypeInformation
} else {
    $outarr
}

Some of the readers of my blog might ask why to use GetHostbyAddress method when Resolve-DNSName can do the task. It is simple; the .Net method works from most of the windows computers in use today, including Windows XP. Using Resolve-DNSName requires you to run from Windows8/Windows Server 2012 or above computers. However, use Resolve-DNSName where you can, because it is simply the latest and lets you query other types of records too. The .Net method lets you query A, AAA and PTR records only.

Usage

You can use this script by passing list of IP addresses to -IPAddress parameter as shown below. The Name column indicates the name the ip resolved to, and the Status column contains whether name resolution is successful or not.

.\Resolve-IpToName.ps1 -IPAddress 69.163.176.252,98.137.246.8

You can input the list of IPAddress using text file as well.

.\Resolve-IpToName.ps1 -IPAddress (get-content c:\temp\ips.txt)

By default, the script shows the output on the screen. If you want to export them to CSV, use -ExportToCSV switch.

.\Resolve-IpToName.ps1 -IPAddress (get-content c:\temp\ips.txt) -ExportToCsv

Above CSV file gets generated when you use -ExportToCSV switch.

Hope you find this article useful. Please write in the comment section if you are looking for additional functionality. We will try to make it on the best effort basis.

How to check DNS resolution?

The hostnames, IPs, ports, required for checking DNS resolution are available in this document. https://docs.cleartax.in/cleartax-docs/clear-finance-cloud/cfc-api-reference#2.-production-environment

The objective of this step is to make sure that the hostnames are resolving to all of the IP’s mentioned in the document, from your ERP.

If you are using a proxy, you should run this from that proxy system.

  1. To verify this, you can try running the nslookup or ping alternative command from the terminal based on your OS and terminal. For more information, refer to the guide below.

  2. If the DNS is not resolving, please use a public DNS.

  3. If public DNS is not allowed as per your IT policy then make sure that the alternative (host file) includes mapping of each hostname to all of the redundant IP addresses.

If it is not successful, try to flush the DNS cache and retry the nslookup command or the alternatives such as Public DNS or the host file configuration or raise a support ticket with your infrastructure and network service provider.

Note: The DNS resolution has to be consistent and successful at any point of time from all the instances from where the API request might be made in future.

Next: If this step is successful, it only means that your system now knows the IP address of the respective hostnames. It still does not confirm that the hostname is reachable from your system.

Make sure when you run the DNS resolution check commands mentioned in this document you are able to see all the IP’s to which the sandbox and production hostnames should resolve.

List of various commands and the terminals in which it will work.

Steps to run nslookup in Command Prompt

The nslookup command is used to query the Domain Name System (DNS) to obtain information about a domain or hostname.

When you perform an nslookup command, it will query the DNS server to get information about the IP address associated with the domain name.

For ensuring if the hostname is resolving to the correct IP address, follow the below steps:

Go to Command Prompt and run the nslookup command as below for both sandbox and production hostnames separately.

Sandbox:

nslookup api-sandbox.clear.in

The output here is non-authoritative because it did not come from the authoritative DNS server for the «clear.in» domain.

If it is successful, you should see the response as shown in the above image which has both the IP addresses.

Repeat the same with the below hostname as well.

nslookup storage.clear.in

Production:

Repeat the same with the below hostname as well.

nslookup storage.clear.in

Steps to run nslookup in PowerShell

Go to Windows PowerShell and run the nslookup command as below for both sandbox and production hostname to check if it is resolving to correct IP’s

Sandbox:

nslookup api-sandbox.clear.in

Repeat the same with the below hostname as well.

nslookup storage.clear.in

Production:

Repeat the same with the below hostname as well.

nslookup storage.clear.in

Alternatively you can also run the Resolve-DnsName command in PowerShell as below for both sandbox and production hostname to check if it is resolving to correct IPs.

Sandbox:

Resolve-DnsName api-sandbox.clear.in

Repeat the same with the below hostname as well.

Resolve-DnsName storage.clear.in

Production:

Resolve-DnsName api.clear.in

Repeat the same with the below hostname as well.

Resolve-DnsName storage.clear.in

Steps to run nslookup in GitBash

Go to GitBash and run the nslookup command as below for both sandbox and production hostname to check if it is resolving to correct IP’s

Sandbox:

nslookup api-sandbox.clear.in

Repeat the same with the below hostname as well.

nslookup storage.clear.in

Production:

Repeat the same with the below hostname as well.

nslookup storage.clear.in

Steps to run nslookup in Ubuntu (Linux)

Go to Ubuntu App and run the nslookup command as below for both sandbox and production hostname to check if it is resolving to correct IP’s

Sandbox:

nslookup api-sandbox.clear.in

Repeat the same with the below hostname as well.

nslookup storage.clear.in

Production:

Repeat the same with the below hostname as well.

nslookup storage.clear.in

Steps to run ping in Command Prompt

The ping command is used to check the connectivity between two networked devices by sending an ICMP echo request packet to the target device and waiting for a response.

Go to Command Prompt and run the ping command as below for both sandbox and production hostnames separately.

Sandbox:

ping api-sandbox.clear.in

This output shows that the ping was successful and that the average round trip time to reach the «api-sandbox.clear.in» server was 7 milliseconds.

The IP address associated with the domain name «api-sandbox.clear.in» is 99.83.130.139, and the ping command was able to reach the server with this IP address.

The 0% packet loss indicates that all the packets sent were received, which means there were no network connectivity issues.

Repeat the same with the below hostname as well.

Production:

Repeat the same with the below hostname as well.

Steps to run ping in Powershell

Go to Powershell and run the ping command as below for both sandbox and production hostnames separately.

Sandbox:

ping api-sandbox.clear.in

Repeat the same with the below hostname as well.

Production:

Repeat the same with the below hostname as well.

Steps to run ping in GitBash

Go to GitBash and run the ping command as below for both sandbox and production hostnames separately.

Sandbox:

ping api-sandbox.clear.in

Repeat the same with the below hostname as well.

Production:

Repeat the same with the below hostname as well.

Steps to run ping in Ubuntu (Linux)

Go to Ubuntu App and run the ping command as below for both sandbox and production hostnames separately.

Sandbox:

ping api-sandbox.clear.in

Repeat the same with the below hostname as well.

Production:

Repeat the same with the below hostname as well.

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.

ResolveDnsName Type PTR Name 8.8.8.8 | SelectObject ExpandProperty NameHost

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.8 with the IP address you want to resolve.

Using nslookup Command

Use the nslookup to get hostname from IP address in PowerShell.

$ipAddress = «213.133.127.245»

nslookup $ipAddress | SelectString Pattern ‘Name:’

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.

Using [System.Net.Dns]::GetHostByAddress Method

Use the [System.Net.Dns]::GetHostByAddress method to get hostname from IP address in PowerShell.

$ipAddress = «8.8.8.8»

$hostEntry = [System.Net.Dns]::GetHostByAddress($ipAddress)

$hostname = $hostEntry.HostName

WriteHost «The hostname associated with IP address $ipAddress is $hostname»

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.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows powershell как запустить bat файл
  • Как выглядит код активации windows 11
  • Работа с вебкамерой в windows 10
  • Случайно закрыл проводник в диспетчере задач windows 10
  • Screenshot tool for windows