Command to find network interface for IP

12

2

With ipconfig I can show the list of network adapters and their settings, e.g. the IP address.

I'm looking for a reverse command that displays the name of the network adapter for a given IP address.

I have tried filtering the output of ipconfig with a command like ipconfig | find "192.168.2.4" but then the adapter name is gone.

My output of ipconfig is (the tricky part seems that I have several addresses on one adapter here):

Windows IP Configuration


Ethernet adapter Local Area Connection:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::xxxx:xxxx:xxxx:xxxx%11
   IPv4 Address. . . . . . . . . . . : 192.168.2.4
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   IPv4 Address. . . . . . . . . . . : 192.168.178.20
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.178.1
                                       192.168.2.1

Ethernet adapter VMware Network Adapter VMnet1:
...

Thomas Weller

Posted 2015-11-21T23:38:12.657

Reputation: 4 102

For a given local address, or to find out what interface routing uses to reach a particular remote address? – Ben Voigt – 2015-11-22T14:11:18.447

@BenVoigt: it's an address assigned to a network interface, so the result should be one adapter only. If it were about routing, the result could be many adapters (potentially with different metrics). – Thomas Weller – 2015-11-22T17:49:20.043

Answers

8

How do I display the name of a network adapter for a given IP address?

This solution does not require any external commands (pcre2grep, sed, etc).

Use the following batch file (getname.cmd):

@echo off
setlocal
setlocal enabledelayedexpansion
set "_adapter="
set "_ip="
for /f "tokens=1* delims=:" %%g in ('ipconfig /all') do (
  set "_tmp=%%~g"
  if "!_tmp:adapter=!"=="!_tmp!" (
    if not "!_tmp:IPv4 Address=!"=="!_tmp!" (
      for %%i in (%%~h) do (
      if not "%%~i"=="" set "_ip=%%~i"
      )
    set "_ip=!_ip:(Preferred)=!"
    if "!_ip!"=="%1" (
        @echo !_adapter!
      )
    )
  ) else (
    set "_ip="
    set "_adapter=!_tmp:*adapter =!"
  )
)
endlocal

Usage:

getname ipaddress

Example:

F:\test>getname 192.168.42.78
Local Area Connection 2
F:\test>

Further Reading

DavidPostill

Posted 2015-11-21T23:38:12.657

Reputation: 118 938

1That's interesting David... almost programming! Your idea made me think, I'm posting my batch solution – SΛLVΘ – 2015-11-23T09:30:20.507

3@SalvoF It is programming. Batch has variables, goto, for, if, functions, macros ... what more do you need? ;) – DavidPostill – 2015-11-23T09:36:03.640

I didn't know this until I wondered what has happened to my network config :-) – Thomas Weller – 2015-11-23T21:39:36.110

@ThomasWeller Do you know yet how it happened? – DavidPostill – 2015-11-23T21:40:09.443

Not exactly. It certainly happened when I set up my 2 DSL lines. I have 2 DSL modems. They competed with DCHP, so I set up a fixed address. But that only used one DSL modem, ignoring the second. Some colleages made it work for 2 modems, potentially by setting 2 fixed addresses. Since that time, some of my batch files (and other stuff) is not working as expected any more. Hence the question. – Thomas Weller – 2015-11-23T21:56:07.047

@ThomasWeller Thanks for the explanation, your help, and the green tick ;) – DavidPostill – 2015-11-23T22:23:18.083

6

You could use this PS one liner:

$addr='192.168.2.4'; get-wmiobject Win32_NetworkAdapterConfiguration |? {$_.ipaddress -contains $addr} |select Description |% {$_.Description}

To use it directly from command line:

powershell "$addr='192.168.2.4'; get-wmiobject Win32_NetworkAdapterConfiguration |? {$_.ipaddress -contains $addr} |select Description |% {$_.Description}"

or if you want to reuse it put it in a script and make the address a parameter

Edit: to get a name as it shows in Win/Ipconfig:

$addr='192.168.2.4'; 
$netconf = get-wmiobject Win32_NetworkAdapterConfiguration |? {$_.ipaddress -contains $addr};
$netconf |% {$_.GetRelated("win32_NetworkAdapter")} | select NetConnectionID |%{$_.NetConnectionID}

(the assignment to intermediary variables is only to make it a bit more readable)

wmz

Posted 2015-11-21T23:38:12.657

Reputation: 6 132

This is cool, and it returns HW name. On my system $powershell is undefined though, I launch those commands with powershell -c from command prompt. On PS command line 1st one-liner runs as well. – SΛLVΘ – 2015-11-22T19:34:07.890

@SalvoF oh that's just a typoo (part of my prompt)... It should be powershell I will correct it – wmz – 2015-11-22T19:59:16.603

This gives "Realtek PCIe GBE Family Controller" instead of "Local Area Connection" on my machine. – Thomas Weller – 2015-11-23T19:33:49.880

1@ThomasWeller which in fact is a name of your network adapter as you per your question. But let me check, logical name should be obtainable as well – wmz – 2015-11-23T21:27:07.880

I tried select Name|% {_.Name} but that didn't work – Thomas Weller – 2015-11-23T21:31:13.163

2It's on another table @wmz. PS rocks though: powershell "$ip = '192.168.2.4';foreach($int in (gwmi Win32_NetworkAdapter)) {gwmi Win32_NetworkAdapterConfiguration -Filter """Index = $($int.index)""" | ? {$_.IPAddress -contains $ip} | % {$int.NetConnectionID} }" – SΛLVΘ – 2015-11-23T23:00:35.090

1@ThomasWeller Check my edit. That was tougher than I thought! Fortunately PS supports GetRelated which eases Associators of methods a bit. – wmz – 2015-11-23T23:08:00.370

GetRelated matches common Index keys I believe. Very useful! – SΛLVΘ – 2015-11-23T23:12:12.103

1@SalvoF Yup I found it – wmz – 2015-11-23T23:12:33.380

@SΛLVΘ your comment is the solution I was looking for. Thank you. – Inbar Rose – 2016-09-06T10:51:07.617

4

I'm looking for a reverse command that displays the name of the network adapter for a given IP address.

Based on everything I tried, this should work seems you say you need to get this information ONLY from the IP address which you already specify in your example.

INTERACTIVE PROMPT FOR IP ADDRESS TO GET NETWORK CONNECTION NAME

(Use WMIC and some batch FOR loop token and delim parsing to get the network connection name for a specified IP address.)

(The result value will echo to a command window and a message box window. It's all batch script but dynamically builds some VBS script functions to simplify the process for anyone that needs.)

@ECHO ON

:SetTempFiles
SET tmpIPaddr=%tmp%\~tmpipaddress.vbs
SET tmpNetConName1=%tmp%\~tmpNetConName1.txt
SET tmpNetConName2=%tmp%\~tmpNetConName2.txt
SET tmpBatFile=%tmp%\~tmpBatch.cmd
SET tmpVBNetCon=%tmp%\~tmpVBNetCon.vbs

IF EXIST "%tmpIPaddr%" DEL /F /Q "%tmpIPaddr%"
IF EXIST "%tmpNetConName1%" DEL /Q /F "%tmpNetConName1%"
IF EXIST "%tmpNetConName2%" DEL /Q /F "%tmpNetConName2%"
IF EXIST "%tmpBatFile%" DEL /Q /F "%tmpBatFile%"
IF EXIST "%tmpVBNetCon%" DEL /Q /F "%tmpVBNetCon%"

:InputBox
SET msgboxTitle=IP ADDRESS
SET msgboxLine1=Enter the IP address to get its Windows connection name
>"%tmpIPaddr%" ECHO wsh.echo inputbox("%msgboxLine1%","%msgboxTitle%")
FOR /F "tokens=*" %%N IN ('cscript //nologo "%tmpIPaddr%"') DO CALL :setvariables %%N
GOTO EOF

:setvariables
SET IPAddress=%~1
FOR /F "USEBACKQ TOKENS=3 DELIMS=," %%A IN (`"WMIC NICCONFIG GET IPADDRESS,MACADDRESS /FORMAT:CSV | FIND /I "%IPAddress%""`) DO (SET MACAddress=%%~A)
FOR /F "USEBACKQ TOKENS=3 DELIMS=," %%B IN (`"WMIC NIC GET MACADDRESS,NETCONNECTIONID /FORMAT:CSV | FIND /I "%MACAddress%""`) DO ECHO(%%~B>>"%tmpNetConName1%"

::: Parse Empty Lines
FINDSTR "." "%tmpNetConName1%">"%tmpNetConName2%"

::: Build Dynamic Batch with ECHO'd Network Connection Value
FOR /F "tokens=*" %%C IN (%tmpNetConName2%) DO ECHO ECHO %%~C>>"%tmpBatFile%"
IF NOT EXIST "%tmpBatFile%" GOTO :NullExit
START "" "%tmpBatFile%"

::: Build Dynamic VBS with Message Box Network Connection Value
FOR /F "tokens=*" %%C IN (%tmpNetConName2%) DO (SET vbNetconName=%%~C)
ECHO msgbox "%vbNetconName%",0,"%vbNetconName%">"%tmpVBNetCon%"
START /B "" "%tmpVBNetCon%"
EXIT /B

:NullExit
ECHO msgbox "Cannot find MAC Address, check to confirm IP Address was correct.",0,"Invalid IP">"%tmpVBNetCon%"
START /B "" "%tmpVBNetCon%"
EXIT /B

ALL ONE-LINERS

NATIVE WINDOWS ONLY WITH NETSH ALL INTERFACES (ALL IPv4 ADDRESSES)

NETSH INT IP SHOW CONFIG | FINDSTR /R "Configuration for interface.* Address.*[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*"

enter image description here

NATIVE WINDOWS ONLY WITH IPCONFIG ALL INTERFACES (ALL IPv4 ADDRESSES)

IPCONFIG | FINDSTR /R "Ethernet* Address.*[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*"

enter image description here


USING PCRE2GREP (per @SalvoF)

SINGLE IP ADDRESS SPECIFIED

netsh interface ipv4 show address | pcre2grep -B2 "192\.168\.2\.4" | FIND /V "DHCP"

FIND ALL IP ADDRESSES

netsh interface ip show config | pcre2grep -B2 ^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$ | FIND /V "DHCP" | FIND /V "Gate" | FIND /V "Metric" | FIND /V "Subnet"

FIND ALL IP ADDRESSES (Cleaned Up Regex (per @SalvoF))

netsh interface ip show config | pcre2grep "^[A-Z]|IP.*([0-9]{1,3}(\.|)){4}"

Please note that the pcre2grep I tried is per @SalvoF [+1] as he suggested but using the.... FIND /V to remove the line above containing DHCP seems to get the desired output as you described. I used NETSH rather than IPCONFIG as well.

Pimp Juice IT

Posted 2015-11-21T23:38:12.657

Reputation: 29 425

This catches some extra information on my machines (as network masks, and such). My point was that in case you have multiple IP addresses, you cease having a "fixed" rule to get to interface name. Initial Q is: given an IP no. how do I find the interface it belongs to? I wasn't looking for all IP's. – SΛLVΘ – 2015-11-22T03:32:52.300

2Thank you for your inputs! BTW, I noticed that leading and trailing lines on my side were due to language issues. To circumvent those, what do you think about this? netsh interface ip show config | pcre2grep "^[A-Z]|IP.*([0-9]{1,3}(\.|)){4}" (I cleaned the regex a bit). I'm learning a lot around this place! – SΛLVΘ – 2015-11-22T05:18:43.887

+1 Thanks for the suggestion. It still has too much output for my usage. – Thomas Weller – 2015-11-23T19:39:03.987

3

To be more accurate, following OP's example, I'd use sed, which can be found under the \usr\local\wbin folder of this zipped file (UnxUtils project).

ipconfig | sed -rn "/^[A-Z]/h;/192.168.2.4/{g;s/.* adapter (.*):/\1/p;}"

-n suppresses non matching lines; first pattern finds any line starting with capital letter, then h puts it away on hold space; second match is on wanted IP number: at this point, line holding interface name is recalled (g), extra leading text stripped (s), and printed (p).

SΛLVΘ

Posted 2015-11-21T23:38:12.657

Reputation: 1 157

-B4 almost works, it just leaves me with the prefix "Ethernet adapter", which does not belong to the adapter name + 4 lines of unrelated output. But the message is clear: find a tool that does it :-) – Thomas Weller – 2015-11-22T00:47:07.193

1Could you update your post to show unfiltered ipconfig output? (Obfuscate or change data for privacy) – SΛLVΘ – 2015-11-22T00:52:23.567

Ok, added. It also seems to be tricky to handle adapters with multiple addresses. – Thomas Weller – 2015-11-22T00:58:07.197

1That's brilliant @PJMahoney. What would be the output with multiple IP addresses though? I made an effort for a general solution by using sed; maybe your solution too can be tweaked to reach that goal. – SΛLVΘ – 2015-11-22T03:10:00.737

The sed one works if I add another | sed -rn "s/^.* adapter (.*):/\1/p" – Thomas Weller – 2015-11-23T21:58:42.007

@ThomasWeller, I missed that additional text. Edited – SΛLVΘ – 2015-11-23T23:31:29.060

2

Just for the record, here's another batch solution, it exploits delayed expansion of the %ERRORLEVEL% system variable:

@echo off
setlocal EnableDelayedExpansion
for /f "delims=" %%L in ('ipconfig') do (
    echo %%L | findstr /r "^[A-Z]" 1>NUL
    if !errorlevel! == 0 set "_int=%%L"
    echo %%L | findstr /c:%1 1>NUL
    if !errorlevel! == 0 (
       set "_int=!_int::=!"
       echo !_int:* adapter =!
       goto:eof
    )
)

It can be invoked this way: find_int.cmd 192.168.1.100

SΛLVΘ

Posted 2015-11-21T23:38:12.657

Reputation: 1 157

Hehe. That is a neat pure batch solution. Well done ;) – DavidPostill – 2015-11-23T09:40:19.903

+1 The output is very close to what I need. Thanks – Thomas Weller – 2015-11-23T19:44:35.187

I edited the sed one-liner, leaving interface name as sole output. Of course, you can write a simple batch file for that too, passing the IP no. as argument (%1). – SΛLVΘ – 2015-11-23T20:19:59.203

@ThomasWeller, tuned this one too. Cheers! – SΛLVΘ – 2015-11-23T23:48:12.953

1

Thanks for the effort everyone. It seems there are several hurdles:

  • the number of IP addresses assigned to an adapter
  • the language of the OS

All the -Bx and Regex stuff seems to break easily, so I googled for something I could implement myself and came up with the following C# program, which takes the IP address as parameter (IP2Adapter <IP>):

using System;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace IP2Adapter
{
    class Program
    {
        static void Main(string[] args)
        {
            var adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (var adapter in adapters)
            {
                var ipProps = adapter.GetIPProperties();
                foreach (var ip in ipProps.UnicastAddresses)
                {
                    if ((adapter.OperationalStatus == OperationalStatus.Up)
                        && (ip.Address.AddressFamily == AddressFamily.InterNetwork))
                    {
                        if (ip.Address.ToString() == args[0])
                        Console.Out.WriteLine(adapter.Name);
                    }
                }
            }
        }
    }
}

Thomas Weller

Posted 2015-11-21T23:38:12.657

Reputation: 4 102

0

On Windows 10 Powershell, this can be achieved with the following:

Get-NetIPAddress -IPAddress '192.168.2.4' | %{$_.InterfaceAlias};

This will give a result such as Wi-Fi.

Where You can substitute InterfaceAlias for any other object property.

To get all properties, simply omit the pipes, and run: Get-NetIPAddress -IPAddress '192.168.2.4'.

Other network adapter related properties (such as Description) can usually be queried based on InterfaceAlias or InterfaceIndex, eg.:

Get-NetAdapter -InterfaceAlias Wi-Fi | %{$_.InterfaceDescription};

Which will give something like: Intel(R) Dual Band Wireless-AC 8265.

Read more on the docs: https://docs.microsoft.com/en-us/powershell/module/nettcpip/get-netipaddress?view=win10-ps

MrMeszaros

Posted 2015-11-21T23:38:12.657

Reputation: 101