Windows dns name by ip

I’m looking for a command line tool which gets an IP address and returns the host name, for Windows.

asked Oct 13, 2009 at 14:27

DouglasJose's user avatar

1

The command you are looking for is called nslookup, works fine for reverse lookups IFF someone has configured a reverse zone file, which they don’t always do.

Bruno Bieri's user avatar

answered Oct 13, 2009 at 14:29

Ward - Trying Codidact's user avatar

0

if all the above fails, and you are specifically looking for a Windows machine, you can use

nbtstat -a 192.168.1.50

The data returned will be all the NetBIOS records the machine has. The one with a <20h> record type will usually be the machine’s name.

answered Oct 13, 2009 at 16:32

Moose's user avatar

MooseMoose

1,6411 gold badge9 silver badges7 bronze badges

7

For many IP addresses you could just use ping -a, for example

ping -a 209.85.229.106

will return

Pinging ww-in-f106.google.com [209.85.229.106] with 32 bytes of data:

Reply from 209.85.229.106...........

answered Oct 13, 2009 at 14:44

Marko Carter's user avatar

Marko CarterMarko Carter

4,0921 gold badge30 silver badges38 bronze badges

4

If you use nslookup command with the IP address as its first argument will return the PTR record (the reverse entry) if it exists. For example:

nslookup 192.168.1.50

answered Oct 13, 2009 at 14:36

Kyle Brandt's user avatar

Kyle BrandtKyle Brandt

83.7k74 gold badges307 silver badges448 bronze badges

(tested under Windows 10 x64)

From command line:

FOR /F "tokens=2 delims= " %A in ('2^>NUL NSLOOKUP "%IP_ADDRESS%" ^| FINDSTR /C:": "') do ECHO %A

Within a script:

FOR /F "tokens=2 delims= " %%A in ('2^>NUL NSLOOKUP "%IP_ADDRESS%" ^| FINDSTR /C:": "') do ECHO %%A

Two (side)notes:

  • To supress NSLOOKUP errors you have to use 2^>NUL instead of 1^>NUL
  • I’ve used FINDSTR /C to extract the value after the four whitespace characters. As the four spaces only seem to exist for the Name: entry, this appears to be only way to make it work on other localized systems.

JimNim's user avatar

JimNim

2,78613 silver badges24 bronze badges

answered Jul 17, 2017 at 14:22

script'n'code's user avatar

script’n’codescript’n’code

1611 gold badge1 silver badge7 bronze badges

Use dig. A Windows port is available from the ISC here (look in the immediate download box for the link to the zip file). Here’s their man page reference for dig.

Ward’s point about the reverse lookup records often not getting created is very much true. Reverse lookups often do fail because many admins don’t bother creating the ptr records.

Marcello Miorelli's user avatar

answered Oct 13, 2009 at 14:35

squillman's user avatar

squillmansquillman

37.9k12 gold badges92 silver badges146 bronze badges

tracert might be an option.

tracert 10.12.190.51

Results in:

Tracing route to LAP8662.aus.int.example.com [10.12.190.51]
over a maximum of 30 hops:

  1    <1 ms    <1 ms    <1 ms  LAP8662.aus.int.example.com [10.12.190.51]

Trace complete.

answered Dec 7, 2022 at 5:14

Fidel's user avatar

FidelFidel

3731 gold badge4 silver badges19 bronze badges

4

if you want to know the host-name in same network then please use another machine which have same network and use below commend
Ping -an ip addres

answered Jun 27, 2017 at 23:34

user422366's user avatar

1

psexec \192.168.0.65 hostname

DMHD006
hostname exited on 192.168.0.65 with error code 0.

answered Jul 25, 2019 at 8:29

Sahin's user avatar

1

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

You might want to try the other solutions offered here, but here are some things you might want to think about.

First, I’d recommend not putting the try{}catch{} around the whole of the first command. If you are looping through data and just one of them causes an exception, you risk not completing the task. Put the try{}catch{} around just the «risky» line of code:

Get-Content C:\Users\pintose\Documents\IP_Address.txt | Foreach-Object {
  try {
    ([system.net.dns]::GetHostByAddress($_)).hostname >> C:\Users\user\Documents\hostname.txt
  }
  catch {
    if ($_.Exception.Message -like "*The requested name is valid*") {
      Write-Output "UNREACHABLE" | Out-File C:\Users\user\Documents\hostname.txt
    }
  }
}

When you catch the exception, you only write to the text file in the case that «the requested name is valid» (do you mean invalid?). You never write anything to the file otherwise. Thus, going back to your original code:

  • IF there is an exception caused by ANY of the IP addresses
  • AND the exception is NOT «the requested name is valid» (which I think might be a typo?)
  • THEN no error gets written to the file and the script ends without necessarily completing all the IP addresses.

Other things:

You use two methods to write to the file: >> and Out-File. Probably better to use the PowerShell cmdlet but with the -Append switch to ensure you append to the end of the file:

([system.net.dns]::GetHostByAddress($_)).hostname | Out-File C:\Users\user\Documents\hostname.txt -Append

Write-Output "UNREACHABLE" | Out-File C:\Users\user\Documents\hostname.txt -Append

@restless1987 has suggested a way to ensure you write both the IP address and the hostname (if determined) to the output file. I’d have a look at that to work out what is going on.

My final tip would be to be wary of reading in from .txt files with Get-Content. They often have trailing (blank) lines and you might want to try to ignore such blanks. Probably not a big issue in this case as it will just mean a failed DNS attempt, but I have seen such things wreak havoc on every mailbox in a (very) large company when used with other commands.

В коммандной строке
nslookup X.X.X.X

Для IP адреса нужно указать обратную зону на DNS, тогда по IP адресу можно прочитать содержимое обратной зоны и получить домен.

для A.B.C.D
nslookup D.C.B.A.in-addr.arpa

А если проблемный хост по какой-либо причине не регистрировался в DNS, или там вручную созданная запись, содержащая неактуальные/неверные данные?

Попробуйте на каком-либо хосте в том же сегменте локальной сети, где и интересующий адрес х.х.х.х:

nbtstat.exe -a x.x.x.x

Попробуй «ping -a 192.168.1.1»
Без кавычек и свой ip подставь

I’m looking for a command line tool which gets an IP address and returns the host name, for Windows.

asked Oct 13, 2009 at 14:27

DouglasJose's user avatar

1

The command you are looking for is called nslookup, works fine for reverse lookups IFF someone has configured a reverse zone file, which they don’t always do.

Bruno Bieri's user avatar

answered Oct 13, 2009 at 14:29

Ward - Trying Codidact's user avatar

0

if all the above fails, and you are specifically looking for a Windows machine, you can use

nbtstat -a 192.168.1.50

The data returned will be all the NetBIOS records the machine has. The one with a <20h> record type will usually be the machine’s name.

answered Oct 13, 2009 at 16:32

Moose's user avatar

MooseMoose

1,6411 gold badge9 silver badges7 bronze badges

7

For many IP addresses you could just use ping -a, for example

ping -a 209.85.229.106

will return

Pinging ww-in-f106.google.com [209.85.229.106] with 32 bytes of data:

Reply from 209.85.229.106...........

answered Oct 13, 2009 at 14:44

Marko Carter's user avatar

Marko CarterMarko Carter

4,0921 gold badge30 silver badges38 bronze badges

4

If you use nslookup command with the IP address as its first argument will return the PTR record (the reverse entry) if it exists. For example:

nslookup 192.168.1.50

answered Oct 13, 2009 at 14:36

Kyle Brandt's user avatar

Kyle BrandtKyle Brandt

83.7k74 gold badges307 silver badges448 bronze badges

(tested under Windows 10 x64)

From command line:

FOR /F "tokens=2 delims= " %A in ('2^>NUL NSLOOKUP "%IP_ADDRESS%" ^| FINDSTR /C:": "') do ECHO %A

Within a script:

FOR /F "tokens=2 delims= " %%A in ('2^>NUL NSLOOKUP "%IP_ADDRESS%" ^| FINDSTR /C:": "') do ECHO %%A

Two (side)notes:

  • To supress NSLOOKUP errors you have to use 2^>NUL instead of 1^>NUL
  • I’ve used FINDSTR /C to extract the value after the four whitespace characters. As the four spaces only seem to exist for the Name: entry, this appears to be only way to make it work on other localized systems.

JimNim's user avatar

JimNim

2,78613 silver badges24 bronze badges

answered Jul 17, 2017 at 14:22

script'n'code's user avatar

script’n’codescript’n’code

1611 gold badge1 silver badge7 bronze badges

Use dig. A Windows port is available from the ISC here (look in the immediate download box for the link to the zip file). Here’s their man page reference for dig.

Ward’s point about the reverse lookup records often not getting created is very much true. Reverse lookups often do fail because many admins don’t bother creating the ptr records.

Marcello Miorelli's user avatar

answered Oct 13, 2009 at 14:35

squillman's user avatar

squillmansquillman

37.9k12 gold badges92 silver badges146 bronze badges

tracert might be an option.

tracert 10.12.190.51

Results in:

Tracing route to LAP8662.aus.int.example.com [10.12.190.51]
over a maximum of 30 hops:

  1    <1 ms    <1 ms    <1 ms  LAP8662.aus.int.example.com [10.12.190.51]

Trace complete.

answered Dec 7, 2022 at 5:14

Fidel's user avatar

FidelFidel

3731 gold badge4 silver badges19 bronze badges

4

if you want to know the host-name in same network then please use another machine which have same network and use below commend
Ping -an ip addres

answered Jun 27, 2017 at 23:34

user422366's user avatar

1

psexec \192.168.0.65 hostname

DMHD006
hostname exited on 192.168.0.65 with error code 0.

answered Jul 25, 2019 at 8:29

Sahin's user avatar

1

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

В повседневной работе, регулярно приходилось сталкиваться с ситуацией, когда на входе имеется список из ip адресов, по которым необходимо провести какие-то операции: обновление, удаление, перезагрузка, выключение. При этом, сами ip адреса без DNS имен не информативны. И вот встает задача, получить из списка IP адресов список, в котором для каждого IP адреса сделана попытка получить его DNS имя. И уже по имени сервера, можно понимать, что это за сервер, кто за него ответственный, какие операции с ним можно выполнять и в какое время.

Получаем из списка IP адресов список DNS имен

Итак, задача сводится к следующему:
На входе: есть файл, в котором в одну колонку перечислены ip адреса. Файл с названием: ip.txt
На выходе: надо получить файл, имеющий 2 колонки: IP адрес, DNS имя сервера (если оно найдено). Результат записать в файл с названием: ipdns.txt c запятой в качестве разделителя.

Один из примеров реализации для PowerShell начиная с версии Windows 8/Windows 2012

$ipaddress=Get-Content -Path C:\Temp\ip.txt # Читаем содержимое файла

$results = @()

ForEach ($ip in $ipaddress)
 { # Обрабатываем построчно, для каждого IP
    $obj=new-object psobject
    
    $hostname = ""
    
    #Выполняем разрешение IP адреса в DNS имя
    $hostname = Resolve-DnsName -Name $ip -Type PTR -ErrorAction SilentlyContinue 

    # записываем в объект полученным результат
    $obj | Add-Member -MemberType NoteProperty -Name ip -Value ($ip)
    $obj | Add-Member -MemberType NoteProperty -Name hostname -Value ($hostname.NameHost)

    #Формируем массив объектов
    $results +=$obj
}
# Выводим результат в файл
$results | Select-Object -Property ip, hostname | Export-Csv C:\temp\ipdns.txt -Encoding UTF8 -Delimiter "," -NoTypeInformation 

В ранних версия PowerShell вместо команды:

Resolve-DnsName -Name $ip -Type PTR

рекомендовалось использовать командлет:

[System.Net.Dns]::GetHostByAddress($ip)

Получаем из списка DNS имен список IP адресов

В случае, если стоит обратная задача, из списка DNS имен, получить список ip адресом, то слегка меняем исходный текст и получаем, следующий скрипт:

$dnsnames=Get-Content -Path C:\Temp\dns.txt # Читаем содержимое файла

$results = @()

ForEach ($dns in $dnsnames)
 { # Обрабатываем построчно, для каждого DNS имени
    $obj=new-object psobject
    
    $ip = ""
    
    #Выполняем разрешение DNS имени в IP адрес
    $ip = Resolve-DnsName -Name $dns -Type A -ErrorAction SilentlyContinue 

    # записываем в объект полученным результат
    $obj | Add-Member -MemberType NoteProperty -Name dns -Value ($dns)
    $obj | Add-Member -MemberType NoteProperty -Name ip -Value ($ip.IPAddress)

    #Формируем массив объектов
    $results +=$obj
}
# Выводим результат в файл
$results | Select-Object -Property dns, ip | Export-Csv C:\temp\ip.txt -Encoding UTF8 -Delimiter "," -NoTypeInformation 

В этом случае исходным файл с dns именами называется dns.txt, а целевой ip.txt

  • Windows device recovery tool ошибка
  • Windows display language только английский как поменять на русский windows 11
  • Windows device recovery tool не устанавливается
  • Windows display language не меняется на русский
  • Windows display language как поставить русский