Network interface names windows

Network interfaces

This topic describes high-level network interface concepts on Windows, including the ways they can be identified in code and their properties.

This topic is intended for a developer audience, both for Windows desktop networking apps and kernel mode networking drivers. Nevertheless, some of the information presented here can also be useful for system administrators managing network interfaces through PowerShell cmdlets.

Overview

A network interface is the point where two pieces of network equipment or protocol layers connect. Typically, this is represented by a physical Network Interface Card (NIC) for connection between a computer and a private or public network. However, it can also take the form of a software-only component such as the loopback interface ( 127.0.0.1 for IPv4 or ::1 for IPv6).

Network interfaces are defined by the Internet Engineering Task Force (IETF) in RFC 2863 and are not meant to be defined by Windows. For detailed questions about the meaning of network interface identifiers such as ifIndex, see the IETF’s definitions of them. The rest of this topic discusses Windows-specific implementation details.

Network interface identifiers and properties

On Windows, a network interface can be identified in different ways. Some of these identifiers are used to distinguish network interfaces from each other, but not all identifiers are equally suited to that task because of their differing properties. Generally, network interfaces are identified by a network address to external components. For example, this may be a node ID and a port number, or simply a unique node ID.

In code, a network interface can be identified in many ways. The following table details the ways a network interface can be identified along with associated properties. We recommend using the interface GUID (ifGuid) for programming unless a specific API requires a different network interface identifier.

In the following table, bolded cells represent a property that is desirable for networking programmers.

Identifier Size Is unique on the system Is unique in the world Is predictable Will be recycled if the NIC is removed Persists across reboots End users can modify at any time Drivers can modify at any time General familiarity with end users Is always present
ifIndex 4 bytes Yes No No Yes No 1 No No Some 2 Yes
NetLuid 8 bytes Yes No No Yes Yes No No No Yes
ifGuid 16 bytes Yes Usually 3 No No Yes No No No Yes
ifAlias 514 bytes Yes for NICs 4 No Sometimes 5 Yes Yes Yes No Yes Usually 4
ifDescr 514 bytes Usually 6 No No Yes Yes No Yes Yes Usually
ifPhysAddress (MAC ADDRESS) 0 to 32 bytes Usually, for NICs Usually, for NICs Yes Tied to hardware Yes No No Yes Usually 7
PnP instance ID Up to 400 bytes Yes No No Yes Yes No No No Usually, for NICs 8
PnP location (PCI slot number) Up to 400 bytes Yes No Yes Yes Yes No No Sometimes Sometimes 8,9

Notes for the preceding table:

  1. IfIndexes are not guaranteed to be stable across reboots, even though they often receive the same value as the previous boot. Therefore, it is not recommended that drivers use ifIndex except where required by an API.
  2. Some netsh commands take ifIndex , or index , as an input. Therefore, some administrative users are familiar with the ifIndex property if they use the netsh command frequently.
  3. If a machine is cloned or imaged, then some of the GUIDs might be the same. Also, certain special network interfaces such as the built-in Teredo interface might have the same GUID on all machines.
  4. NetCfg enforces that an ifAlias is a non-empty string and is unique among all NICs. However, the NDIS interface provider does not. Thererfore, it is possible to find special network interfaces with duplicate or empty names. This is most commonly seen with LBFO teams.
  5. Only if the firmware supports Consistent Device Naming. Typcically, servers have this feature.
  6. NetCfg assigns unique ifDescrs to all network interfaces. However, drivers can call an API to change the ifDescr to anything, including something that is not unique. Some 3rd party software packages do this.
  7. Not all media types have a «MAC address.» For example, some tunnels do not have this concept and simply advertise a zero-length byte array as their network address.
  8. Only present on network interfaces that are backed by a PnP device. For example, loopback interfaces, light weight filter interfaces, interfaces provided by an NDIS interface provider, and certain special built-in NICs don’t have PnP devices backing them.
  9. Only some PnP buses support a PnP location ID. The built-in PCI and USB buses do, while root-enumerated devices do not.

Visibility to developers

In the preceding table, all properties except for the Plug and Play (PnP) properties are visible to user mode desktop apps and kernel mode drivers via a shared header (Netioapi.h). The PnP properties are visible via the Devpkey.h header and are used by both user mode desktop apps and kernel mode drivers. For example, see the DEVPKEY documentation.

The IP Helper API is also available for both user mode desktop apps and kernel mode drivers.

The UWP API surface only exposes the ifGuid property directly. However, it is possible for a UWP app developers to import the GetIfTable2 function using P/Invoke if they are required to access other network interface properties.

For management information base (MIB) definitions for network interfaces, see RFC 2863.

For NDIS network interfaces in network drivers, see NDIS Network Interfaces.

For Netioapi.h API reference, see netioapi.h header.

Network interface names windows

Netsh — настройка сети в Windows из командной строки cmd

Любой системный администратор сталкивается с настройкой сетевых интерфейсов. Большинство для этой цели используют графический интерфейс Windows, что не всегда удобно. В этой статье я расскажу, как настроить сеть с помошью интерфейса командной строки cmd, используя встроенную утилиту netsh.

В операционных системах Windows есть специальная утилита netsh для настройки сетевого адаптера из командной строки cmd.

netsh.exe (network shell) — сетевая оболочка (программа) для ОС Windows, которая позволяет настраивать сетевые параметры, в том числе и удаленно. Данная утилита доступна на всех версиях Windows, начиная с Windows 2000.

Запуск командной строки:

Пуск —> Выполнить —> в строку вводим cmd.exe

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

Конфигурирование сетевых параметров (ip-адреса, сетевой маски и шлюза)

Уснановка ip-адреса, маски и шлюза.

где
Local Area Connection — название вашего сетевого интерфейса.
192.168.1.15 — сетевой адрес (ip address).
255.255.255.0 — сетевая маска (network mask).
192.168.1.1 — шлюз (default gateway).

Установка дополнительного ip-адреса.

Включение автоматического получения ip-адреса, сетевой маски и шлюза от DHCP-сервера.

Конфигурирование DNS и WINS серверов

Добавить предпочитаемый DNS сервер.

Добавить альтернативный DNS сервер.

Добавить 3-й DNS сервер.

Установка автоматического получения предпочитаемого и альтернативного dns-сервера от DHCP-сервера.

Включение и отключение сетевых интерфейсов

Просмотр сетевых настроек

Расширеный вывод конфигурации сетевых интерфейсов.

Просмотр состояния интерфейсов (connected/disconnected).

Просмотр таблицы маршрутизации.

Просмотр конфигурации IP-адресов.

Просмотр адресов DNS-сервера.

Просмотр адресов WINS-сервера.

Сохранение и восстановление конфигурации сетевых интерфейсов

Ну а теперь самое интересное. Поговорим о том, как сохранить сетевые настройки в виде файла конфигурации и восстановить из файла конфигурации. Это может пригодиться тем, кто постоянно меняет сетевые настройки.

Сохранить сетевые настройки в виде файла.

Восстановить сетевые настройки из файла конфигурации.

Вот и все. Мы рассмотрели далеко не все возможности утилиты Netsh.exe, а лишь самые часто используемые. Используя коммандную строку Windows и утилиту netsh можно намного облегчить себе жизнь.

1″ :pagination=»pagination» :callback=»loadData» :options=»paginationOptions»>

Renaming the network interface name via command line

I want to rename the network interface name to a default name, for example «Ethernet», via dos.

I know netsh interface set interface name=”Local Area Connection” newname=”Ethernet” is the way to do it.

I am running a script and it will not know the name of the interace, correct? So, I need it to rename it to a default before I set the IP address for the interface.

How can I do this without knowing the name of the interface?

Is there a way to get the name of the interface somehow and then change it?

2 Answers 2

netsh (a tool MS tried to wean us off and gave up)

To get the WLAN interface names: netsh wlan show interfaces
help states: show interfaces — Shows a list of the wireless LAN interfaces on the system.
To get LAN interface names: netsh lan show interfaces
help states: show interfaces — Shows a list of the current wired interfaces on the system.
To get names of all interfaces: netsh interface show interface
help states: show interfaces — Displays interfaces.

The command for LAN does need Wired AutoConfig service, which is usually not started.

This Batch script would start the service, get (the last) LAN interfaces name, change it to a new name, stop the Wired AutoConfig service again.

  • It assumes there is only one wired interface
  • It will stop Wired AutoConfig service whether it was running or not at the start

For Wifi interfaces, change in above script ‘lan’ to ‘wlan’ and remove both sc.exe service start/stop

PowerShell

To get better control of what interface is renamed PowerShell will be an easier choice.

This will probably work in most cases:
Get-NetAdapter | Where-Object < $_.HardwareInterface -eq $True -and $_.MediaType -eq "802.3" >| Rename-NetAdapter -NewName «Ethernet»

HardwareInterface will eliminate virtual interfaces, e.g. VMWare
MediaType 802.3 will only show «wired» interfaces and not Wifi, Broadband or others.

In a script file, use the above version of the command, shorthand version would be:
Get-NetAdapter | ? HardwareInterface | ? MediaType -eq «802.3» | Rename-NetAdapter «Ethernet»

There are more options how to select the desired interface. Check all parameters by which it can be selected:
(Get-NetAdapter)[0] | Format-List -Property * -Force

e.g.
List all made by Realtek (Realtek vendor 10ec, Intel: 8086):
Get-NetAdapter | ? ComponentID -like «PCI\VEN_10EC*»

Not virtual:
Get-NetAdapter | ? Virtual -eq $false

Connector Present:
Get-NetAdapter | ? ConnectorPresent

Then there is WMI object
Get-WmiObject -Class Win32_NetworkAdapterConfiguration

Registry

In a case that you changed a Network adapter card and a new one is using a name: Ethernet 2 or similar and you want to rename it back to «Ethernet», there will be an error saying:

Which is of course erroneous error message about renaming a computer.
PowerShell would say correctly: An attempt was made to create an object and the object name already existed.

But going to Control Panel\Network and Internet\Network Connections and trying to rename the interface there would not help either.

It seems the only option for such case is to find corresponding key in these registry paths:

and remove the key for the old interface (not the whole paths as written above!), then restart.
Renaming by cmd batch, PS or in Control Panel should now work.

On Windows how to get network interface name whether its eth0/eth1/eth2 using batch script?

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:

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.

This scripts gives hostname/computername.

Please help me to get network interface name.

Thanks a lot. regards, Yeshwant

2 Answers 2

This should give you the Network Interface Name:

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

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:

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).

Читайте также:  Зайти по ftp linux
Оцените статью