Как узнать имя сетевого интерфейса windows

cmd

  • cmd/bat

Добрый день.
Для bat-скрипта требуется сделать вывод имен и выбор сетевого интерфейса для дальнейшей работы с ним.
Не могу найти, как сделать вывод только имен в стиле:

Сетевое подключение 1
Сетевое подключение 2

IPCONFIG выдает много лишней информации для этого.
Подскажите. как сделать или что гуглить?


  • Вопрос задан

  • 4954 просмотра


Комментировать


Решения вопроса 1

ipconfig | find «Адаптер»
зы: еще можно так netsh interface ipv4 dump, весь вопрос — зачем

  • Нужно создать батник для смены сетевых настроек «для блондинок».
    Т.к. на компах по разному названы сетевые подключения, нужно сделать максимально простой выбор адаптеров для применения настроек.

  • Денис Давыденко, Фильтровать вывод для получения нужной информации — обычная практика. Большинствуо консольных утилит выводит слишком много не нужной в конкретном случае информации.
    Для фильтрации обычно используют: find, findstr
    Для разделения вывода на поля: for /f
    Для справки:

    find /?
    findstr /?
    for /?

  • Korben5E, в этом примере прописано конкретное имя адаптера. Моя цель, что бы не менять это название вручную, а выбирать нужный адаптер в консоли.
    У меня проблема не в том, как реализовать настройку, а как вывести имена адаптеров без лишней информации.

  • Денис Давыденко, вы не можете знать конкретное имя, просто представьте что есть 2 работающих адаптера :-)

    Самый простой вариант это предлагать выбор из списка, т.е. вывел список и батник спрашивает «введите номер адаптера», далее по шаблону.

  • Korben5E, вот именно это я и пытаюсь сделать) С вашего ответа смог правильнее погуглить решение проблемы и все вышло.

Пригласить эксперта


Похожие вопросы


  • Показать ещё
    Загружается…

09 окт. 2023, в 18:30

8000 руб./за проект

09 окт. 2023, в 18:18

1000 руб./за проект

09 окт. 2023, в 18:11

15000 руб./за проект

Минуточку внимания

I am working on windows and wanted to get the network interface name whether its eth0, eth1, eth2 etc etc etc. I wrote java program and by passing host/computer name I can find out ip address and thereafter based on an ip address I can find out network interface name. The code is as below:

public static String getNetworkInterface() {
        try {
            String computerHostName = "dummy";
            if(!computerHostName.equals("Unknown Computer")) {
                InetAddress address = InetAddress.getByName(computerHostName); 
                return NetworkInterface.getByInetAddress(address).getName();
            }
            else {
                return null;
            }
        }
        catch (SocketException e) {
            e.printStackTrace();
        } 
        catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

The above method returns the value something like eth0/eth1/eth2 etc.

Same thing I want to achieve using batch script on windows. I wrote following script which is providing hostname and an ip address. But I don’t know as to how to get the network interface name.

for /f "skip=1 delims=" %%A in (
  'wmic computersystem get name'
) do for /f "delims=" %%B in ("%%A") do set "compName=%%A"

echo hostname is %compName%

This scripts gives hostname/computername.

Please help me to get network interface name.

Thanks a lot.
regards,
Yeshwant

asked Nov 28, 2016 at 8:58

Yeshwant KAKAD's user avatar

Yeshwant KAKADYeshwant KAKAD

2791 gold badge6 silver badges16 bronze badges

6

This should give you the Network Interface Name:

@Echo Off
For /F "Skip=1Delims=" %%a In (
    '"WMIC NIC Where (Not NetConnectionStatus Is Null) Get NetConnectionID"'
) Do For /F "Tokens=*" %%b In ("%%a") Do Echo=%%b
Timeout -1

answered Nov 28, 2016 at 10:35

Compo's user avatar

4

If you want to find the network interface based on a IP-address you can use:

@echo off
SetLocal EnableDelayedExpansion

set ownIP=W.X.Y.Z
set netifc=
FOR /F "tokens=4*" %%G IN ('netsh interface ipv4 show interfaces ^| findstr /I "[^a-zA-Z]connected"') DO (
    REM set /P =interface %%G is connected < nul >> !progress!
    netsh interface ipv4 show addresses "%%H" | findstr /c "%ownIP%" > nul 2>&1
    IF !ERRORLEVEL! EQU 0 (
        set netifc=%%H
    )
)

:outLoop
echo IP-address %ownIP% from interface %netifc%
EndLocal
exit /b 0

I use netsh instead of WMIC because I don’t have much experience in WMIC but netsh is sufficient in your case.
Note that the SetLocal EnableDelayedExpansion is very important as this script is based on checking the ERRORLEVEL. The cmd-parser parses every block of commands delimited with () as being one single command as if it was written on one line (in our case FOR ... ( ... ) ). It is thus impossible to use a changing variable with its updated value inside a () unless you use delayed expansion. If you don’t, only the value before entering the block can be used. As ERRORLEVEL can change in each iteration (will be 0 if the IP-address has been found by the findstr above it in the addresses of an interface or 1 if it hasn’t), we always need the updated value. This is also why I use !ERRORLEVEL! instead of the classic %ERRORLEVEL%.
More info about EnableDelayedExtension can be found here.

Running the script above with set ownIP=127.0.0.1 (don’t forget to change to your IP) gives the following result:

>search_interface.bat
IP-address 127.0.0.1 from interface Loopback Pseudo-Interface 1

If you’d like to pass the IP-address as an argument each time you call the script, use set ownIP=%~1 (but don’t forget to add a check if an argument has been passed in that case).

Hope it helps.

Good luck!

answered Nov 28, 2016 at 12:12

J.Baoby's user avatar

J.BaobyJ.Baoby

2,1772 gold badges11 silver badges17 bronze badges

6

6 / 6 / 1

Регистрация: 23.09.2011

Сообщений: 15

1

Как определить имя сетевого интерфейса

19.10.2011, 11:21. Показов 29678. Ответов 3


Студворк — интернет-сервис помощи студентам

как автоматически получить переменную содержащую имя интерфейса что бы включить его в скрипт, если точнее, то имя интерфейса через который машина подключена к windows домену (это требуется для написания скрипта выполняемого при входе в домен) Заранее спасибо за любую помощь.



0



251 / 239 / 16

Регистрация: 31.12.2009

Сообщений: 324

19.10.2011, 15:07

2

распарсить вывод (на bat/cmd или vbs/js)

оно?



0



6 / 6 / 1

Регистрация: 23.09.2011

Сообщений: 15

21.10.2011, 13:52

 [ТС]

3

Цитата
Сообщение от buggydancer
Посмотреть сообщение

распарсить вывод (на bat/cmd или vbs/js)

оно?

как бы так я и думал сделать изначально, но останавливают несколько проблем:
почти полное незнание bat/cmd или vbs/js (на sh/bash c sed/grep мне сподручнее),
какой интерфейс то ловить непонятно? писать велосипед для проверки связи тут вообще не разумно — почти наверняка система хранит через какой интерфейс работает с доменом, но где — пока поиск не дал ответов…..



0



atributz

835 / 349 / 12

Регистрация: 04.10.2009

Сообщений: 589

22.10.2011, 20:10

4

имя домена прописано в системной переменной
ну а ip домена определяется с помощью dns. ping по домену должен определять ip.
ну и с помощью таблицы маршрутизации route можно определить ip только вот тут сложности.
дальше через wmic определяется ну и соответственно на весь скрипт потребуются админские права.

Добавлено через 2 часа 34 минуты

Windows Batch file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
@echo off
SetLocal enabledelayedexpansion
if not defined userdnsdomain goto error6
set dom=%userdnsdomain%
for /f "tokens=3 delims=: " %%i in ('ping -n 1 %dom%^| findstr /r /c:" [0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*: "') do set ip=%%i
if "%ip%"=="" goto error1
for /f "tokens=1-4 delims=." %%a in ("%ip%") do (set i1=%%a&set i2=%%b&set i3=%%c&set i4=%%d)
for /f "tokens=4" %%i in ('route print %i1%.%i2%.%i3%.%i4% ^| findstr /r /c:"[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]* "') do set ifc=%%i
if defined ifc goto getdesc
for /f "tokens=4" %%i in ('route print %i1%.%i2%.%i3%. ^| findstr /r /c:"[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]* "') do set ifc=%%i
if defined ifc goto getdesc
for /f "tokens=4" %%i in ('route print %i1%.%i2%. ^| findstr /r /c:"[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]* "') do set ifc=%%i
if defined ifc goto getdesc
for /f "tokens=4" %%i in ('route print %i1%. ^| findstr /r /c:"[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]* "') do set ifc=%%i
if defined ifc goto getdesc
for /f "tokens=4" %%i in ('route print 0.0.0.0 ^| findstr /r /c:"[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]* "') do set ifc=%%i
if not defined ifc goto error2
:getdesc
if %ifc%==127.0.0.1 goto error5
set ifcn=1
for /f "tokens=1,* delims==" %%i in ('wmic nicconfig where ipenabled^=true get ipaddress^,description /format:list ^|findstr "="') do (
if defined %%i!ifcn! set /a ifcn+=1
set %%i!ifcn!=%%j
)
for /l %%i in (1,1,%ifcn%) do (
call set x=%%IPAddress%%i%%
if -!x!==-{"%ifc%"} set num=%%i
)
if "%num%"=="" goto error3
call set descr=%%Description!num!%%
for /f "tokens=1,* delims==" %%i in ('wmic nic where Description^="%descr%" get NetConnectionID /format:list ^|findstr "="') do (
set name=%%j
)
if not defined name goto error4
echo %name%
pause
exit
:error1
echo not find ip domen
pause
exit
:error2
echo not find interface
pause
exit
:error3
echo not find interface description
pause
exit
:error4
echo not find interface name
pause
exit
:error5
echo its ip local host
pause
exit
:error6
echo no have dnsdomain
pause
exit

Добавлено через 4 минуты
В случае если ip домена постоянно а по имени он не пингуется, то можно ip не вычислять а сразу домена прописать.



1



Here is a wmic solution resulting with echo =!HostName!,!NetConID!,!IP_Addrs!,!MAC_Addr! with one line for each active adapter of a local computer (can’t try adaptations necessary to run it against a remote machine):

@ECHO OFF >NUL
@SETLOCAL enableextensions enabledelayedexpansion
set "HostName="
wmic computersystem get name ^
  /format:textvaluelist.xsl>"%temp%\cmptr.txt" 2>nul
for /F "tokens=1* delims==" %%G in ('type "%temp%\cmptr.txt"') do (
  if /i "%%G"=="Name" set "HostName=%%~H"
)
set "MAC_Addr="
for /F "tokens=1* delims=:" %%G in ('ipconfig /all^|find /i "Physical Address"') do (
  set "foo="
  for %%I in (%%~H) do if not "%%~I"=="" set "foo=%%~I"
  set "MAC_Addr=!foo:-=:!"
  set "NetConID="
  wmic nic where "NetEnabled='true' and MACAddress='!MAC_Addr!'" ^
    list /format:textvaluelist.xsl>"%temp%\wmcnc.txt" 2>&1
  for /F "tokens=1* delims==" %%I in ('type "%temp%\wmcnc.txt"') do (
    if /i "%%I"=="NetConnectionID" set "NetConID=%%~J"
  )
  set "IP_Addrs="
  wmic nicconfig where "IPEnabled='True' and MACAddress='!MAC_Addr!'" ^
    list /format:textvaluelist.xsl>"%temp%\wmcnccfg.txt" 2>&1
  for /F "tokens=1* delims==" %%I in ('type "%temp%\wmcnccfg.txt"') do (
    if /i "%%I"=="IPAddress" set "IP_Addrs=%%~J"
  )
  if not "!NetConID!,!IP_Addrs!"=="," (
    @echo =!HostName!,!NetConID!,!IP_Addrs!,!MAC_Addr!
  )
)
:endlocal
del "%temp%\cmptr.txt" 2>nul
del "%temp%\wmcnc.txt" 2>nul
del "%temp%\wmcnccfg.txt" 2>nul
@ENDLOCAL
goto :eof

Another solution parses semi-linear output from ipconfig /ALL and gives results closest to previous wmic one as follows:

@ECHO OFF >NUL
@SETLOCAL enableextensions enabledelayedexpansion
  set "HostName="
  set "NetConID="
  set "IP_Addr4="
  set "IP_Addr6="
  set "MAC_Addr="
for /F "tokens=1* delims=:" %%G in ('ipconfig /ALL') do (
  set "foo=%%~G"
  if not "!foo:Host name=!"=="!foo!" (
    for %%I in (%%~H) do if not "%%~I"=="" set "HostName=%%~I"
  )
  if "!foo:adapter=!"=="!foo!" (
    if not "!foo:Physical Address=!"=="!foo!" (
      for %%I in (%%~H) do if not "%%~I"=="" set "MAC_Addr=%%~I"
    )
    if not "!foo:IPv4 Address=!"=="!foo!" (
      for %%I in (%%~H) do if not "%%~I"=="" set "IP_Addr4=%%~I"
      set "IP_Addr4=!IP_Addr4:(preferred)=!"
    )
    if not "!foo:local IPv6 Address=!"=="!foo!" (
      for %%I in (%%~H) do (
        if not "%%~I"=="" (
          for /F "delims=%%" %%p in ("%%~I") Do set "IP_Addr6=%%~p"
          rem set "IP_Addr6=!IP_Addr6:(preferred)=!"
        )
      )
    )
  ) else (
    if not "!IP_Addr6!,!IP_Addr4!"=="," (
      @echo #!HostName!,!NetConID!,{"!IP_Addr4!","!IP_Addr6!"},!MAC_Addr!
    )
    set "MAC_Addr="
    set "IP_Addr4="
    set "IP_Addr6="
    set "NetConID=!foo:*adapter =!"
  )
)
if not "!IP_Addr6!,!IP_Addr4!"=="," (
  @echo =!HostName!,!NetConID!,{"!IP_Addr4!","!IP_Addr6!"},!MAC_Addr!
)

:endlocal
@ENDLOCAL
goto :eof

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.

  • Как узнать какая у меня версия windows 10
  • Как узнать какая битность системы windows 10
  • Как узнать какая звуковая карта стоит на ноутбуке windows 10
  • Как узнать какая у меня аудиокарта на windows 10
  • Как узнать имя рабочей группы windows 10