Linux network device name

How to find network interface name

which is fine, but some machines for some reason use eth1 instead of eth0. I would like to be able to discover the LAN iface name, so I can substitute it in here instead of eth0. Of course, if you can come up with a different oneliner that does the same thing, all good.

display the most active ethernet interface: arp -n -H ether | perl -ne ‘print $1 if /(\S+\n)$/’ | sort | uniq -c | grep -v Iface | sort -n | tail -1 | perl -pe ‘s/.* //’

7 Answers 7

The main NIC will usually have a default route. So:

ip -o -4 route show to default 
ip -o -4 route show to default | awk '' 
ip -o -4 route show to default | awk '' 

Unlike ifconfig, ip has a consistent & parsable output. It only works on Linux; it won’t work on other Unixen.

Not sure if this helps, but it seems that ip route get will show which interface it uses to connect to a remote host.

ubuntu@ip-10-40-24-21:/nail/srv/elasticsearch$ ip route get 8.8.8.8 8.8.8.8 via dev eth0 src

of course you could automate that in shell script with something like,

It seems like on my Ubuntu 15.10 machine this shows the IP address instead of the interface name. @user150471 ‘s answer below works: stackoverflow.com/a/30201105/1069083

Very good! I like this answer because of its versatility in different situations. All one really needs to know is the Ip address of a destination; ip route takes it from there.

Most recenttly systemd/udev has automatically started to assign interface names for all local Ethernet, WLAN and WWAN interfaces to something that we’re all accustomed to . This is a departure from the traditional interface naming scheme («eth0», «eth1», «wlan0», . ) .. now we have to check first what the local interface name is before we can use it while previously we it was a pretty accurate guess that «eth0» was the right name. What you’re asking for is the network NAME .. Here’s a small script to solve the problem

  1. Use «ip route get 8.8.8.8 » to figure out which ACTIVE interface has the route to internet ( or currently being used ) Output should look like : 8.8.4.4 via 10.10.1.1 dev enp0s3 src 10.10.1.118 cache
  2. Use awk to print the 5th text block for Interface NAME ]# ip route get 8.8.8.8 | awk — » Output : enp0s3
  3. Use awk to print the 7th text block for Interface Address ]# ip route get 8.8.8.8 | awk — » Output : 10.10.1.118

Great answer. I find that the ip command outputs two lines («cache and ipid 0x2e6e» on 2nd line). So ip route get 8.8.8.8 | head -n1 | awk — ‘‘ works for me!

Читайте также:  Linux mint wireless lan

Источник

Список сетевых интерфейсов Linux

В операционной системе Linux не только жесткие и SSD диски представлены файлами в специальной файловой системе, но и сетевые интерфейсы. Существует несколько способов посмотреть список сетевых интерфейсов Linux, но самый простой из них — это просто посмотреть содержимое папки в файловой системе.

В этой небольшой статье мы рассмотрим все основные способы выполнить эту задачу в терминале или графическом интерфейсе.

Список сетевых интерфейсов Linux

Сетевые интерфейсы проводного интернета Ethernet обычно имеют имя, начинающиеся с символов enp, например, enp3s0. Такое именование используется только если ваш дистрибутив использует systemd, иначе будет применена старая система именования, при которой имена начинаются с символов eth, например eth0. Беспроводные сетевые интерфейсы, обычно называются wlp или wlx при использовании systemd, например, wlp3s0. Без использования systemd имя беспроводного интерфейса будет начинаться с wlan, например wlan0. Все остальные интерфейсы обычно виртуальные. Один из самых основных виртуальных интерфейсов — lo. Это локальный интерфейс, который позволяет программам обращаться к этому компьютеру. А теперь рассмотрим несколько способов посмотреть их список.

1. Файловая система

Все файлы устройств сетевых интерфейсов находятся в папке /sys/class/net. Поэтому вы можете посмотреть её содержимое:

2. Утилита ifconfig

Утилита ifconfig выводит не только список сетевых интерфейсов, но и информацию о них, такую как состояние, IP адрес, MAC адрес и другие параметры. Для отображения всех интерфейсов достаточно выполнить программу без параметров:

3. Утилита ip

Программа ifconfig устарела и ей на смену пришла утилита ip. Она объединяет в себе функции нескольких программ, например ifconfig, route, brctl и других. Посмотреть список устройств с помощью ip можно выполнив команду:

Здесь информации намного меньше, показывается только состояние устройства, MTU и ещё несколько параметров. Можно вывести информацию в более компактном виде, использовав опцию -br:

В таком случае все данные отображаются в одну строчку, выводится состояние, MAC адрес и ещё несколько опций.

4. Утилита nmcli

Посмотреть всю нужную информацию можно и с помощью консольной утилиты управлением брандмауэром — nmcli:

Здесь выводится подключение NetworkManager, связанное с конкретным устройством, а также его состояние.

5. Утилита netstat

Программа netstat тоже умеет показывать сетевые интерфейсы и статистику по переданным данным если ей передать опцию -i:

6. Файл /proc/net/dev

В файле /proc/net/dev тоже содержится список всех сетевых интерфейсов, а также статистика их использования:

Выводы

Теперь вы знаете как посмотреть сетевые интерфейсы в Linux, как видите, это очень просто сделать. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to get device name from scan like nmap on Linux

I know that I can use a tool like NMAP or arp-scan on Linux to identify the IP and MAC addresses of all devices on my local network. I also know that arp-scan will do a MAC address lookup to get the device manufacturer. But is there any set of options on these commands (or any other command) that can tell me the actual device name of the device at a give IP? For example, if «Joe’s iPad» is on 192.168.1.113 I want a command to get that name.

Читайте также:  Route delete примеры linux

@Marc Doesn’t your nmap -v -sP 192.168.1.0/24 | grep up. give you host-names? Mine for example gives Host XPS8500.fritz.box (192.168.1.33) appears to be up. .

if you know the dns server you can try nmap -A -v —dns-servers 10.10.10.10 10.20.20.20 where 10.10.10.10 is the dns server and 10.20.20.20 is the target

2 Answers 2

Nmap

Some hosts could simply be configured to not share that information. It should work just like this:

user@host:~$ nmap 192.168.1.113 Starting Nmap 7.00 ( https://nmap.org ) at 2015-12-11 08:45 AWST Nmap scan report for Joes iPad (192.168.1.113) Host is up (0.0038s latency). Not shown: 999 closed ports PORT STATE SERVICE 62078/tcp open iphone-sync Nmap done: 1 IP address (1 host up) scanned in 41.88 seconds 

You can force Nmap to attempt reverse DNS resolution for all targets, by using the following option:

-R (DNS resolution for all targets). Tells Nmap to always do reverse DNS resolution on the target IP addresses. Normally reverse DNS is only performed against responsive (online) hosts. 

This might help in some cases. The output will look more or less identical:

user@host:~$ nmap -R 192.168.1.113 Starting Nmap 7.00 ( https://nmap.org ) at 2015-12-11 08:46 AWST Nmap scan report for joes-ipad.local (192.168.1.113) Host is up (0.0047s latency). rDNS record for 192.168.1.113: joes-ipad.local Not shown: 999 closed ports PORT STATE SERVICE 62078/tcp open iphone-sync Nmap done: 1 IP address (1 host up) scanned in 42.61 seconds 

Either way; you can always parse the output through external tools, such as grep . This can be particularly useful if you’re scanning several addresses, or even whole network ranges at a time:

user@host:~$ nmap 192.168.1.0/24 | grep '(192.168.1.113)' Nmap scan report for Joes iPad (192.168.1.113) All 1000 scanned ports on Joes iPad (192.168.1.113) are closed 
user@host:~$ nmap -R 192.168.1.0/24 | grep '(192.168.1.113)' Nmap scan report for Joes iPad (192.168.1.113) All 1000 scanned ports on Joes iPad (192.168.1.133) are closed 

Net-Tools

What you (probably) actually want to do, is this:
*Output will vary, based on OS & software version.

user@gnu:~$ arp 192.168.1.113 Address HWtype HWaddress Flags Mask Iface Joes iPad ether a1:b2:c3:d4:e5:f6 C wlan0 
user@bsd:~$ arp 192.168.1.113 Joes iPad (192.168.1.113) at a1:b2:c3:d4:e5:f6 on en0 ifscope [ethernet] 

Источник

Detecting the name of a network device in bash?

I’m trying to drum up a hack that will output the name of active network devices on one’s computer via bash. I’m making it for work. How do I go about doing this? I don’t want to just plainly use «wlan0» or «eth0» or any of that generic crap because some OSes use different names (Like pfSense for example).

3 Answers 3

It depends what you mean by ‘active’ — if you just want to see the names of all the network devices on the system, you can look at the contents of the /sys/class/net directory e.g.

$ ls /sys/class/net eth0 lo wlan0 

To see the status, you could use the ip command on any link objects — you can parse the output to get the particular fields you want e.g. to see just the device name and state

$ ip -o link show | awk '' lo: UNKNOWN eth0: DOWN wlan0: UP 

If you are running a modern desktop version of Ubuntu (with interfaces managed by the network-manager service), then you should be able to get a similar device status list using nmcli

$ nmcli dev status DEVICE TYPE STATE wlan0 802-11-wireless connected eth0 802-3-ethernet unavailable 

or, to limit the output to particular fields in a way that’s more easily used in a script

$ nmcli --terse --fields DEVICE,STATE dev status wlan0:connected eth0:unavailable 

If you are using network-manager, you could also access device and connection properties via DBUS — see for example Dbus Tutorial — Fun with Network Manager

Читайте также:  Install office 2010 linux

Источник

Get network interface name and MAC address on command line

Interestingly, you can also do it by ifconfig | grep HW | awk ‘< print $1" : "$5 >‘ . Since loopback doesn’t have a HW address, grep will ignore lo .

8 Answers 8

You can get the MAC address from /sys/class/net//address :

$ cat /sys/class/net/enp0s3/address 08:00:27:15:dc:fd 
find /sys/class/net -mindepth 1 -maxdepth 1 ! -name lo -printf "%P: " -execdir cat <>/address \; 
enp0s3: 08:00:27:15:dc:fd docker0: 02:42:61:cb:85:33 

Or, using ip ‘s one-line mode, which is convenient for scripting:

$ ip -o link | awk '$2 != "lo:" ' enp0s3: 08:00:27:15:dc:fd docker0: 02:42:61:cb:85:33 

The /sys directory has been a feature of the Linux kernel since before version 2.6 and as such should be available on all distributions.

ip -o link | grep ether | awk '< print $2" : "$17 >' 
  • where -o gives on-line result for every interface.
  • grep ether filters out only those interface that have a Ethernet address assigned to it.
  • And awk simply prints the 2nd & 17th column from the lines with a colon in between.
ip -br link | grep -v LOOPBACK | awk '< print $1 " : " $3 >' 
  • -br gives the brief information of interfaces.
  • grep -v LOOPBACK ignores the word LOOPBACK that is present only in lo interface.
  • And awk prints first & 3rd column.

Using ifconfig

where grep HW filters out only those interface that have a hardware address assigned to it.

The Hack

grep HW or grep ether actually ignores the lo because

With no arguments xargs will replace all newlines, tabs and multiple spaces to single space. By adding -n 2 it will slice that line after each second word. So:

I made an ugly hacky one liner:

 ip link | awk -F' ' '' | paste -d " " - - | grep -v lo: 

If you count the fields using space as separators you will see the fields you need are the 2nd and 17th.

But they will be printed one under the other, the paste places the adjacent lines as colums. The paste fix that placing adjacent lines side by side in a line. I could not find a smart way to avoid getting the lo line so I just excluded it before printing with grep

ip link | awk -F' ' '' | paste -d " " - - | grep -v lo: enp2s0: 50:9a:4c:b5:af:ea wlp3s0: e8:9e:b4:66:e3:ea 

Источник

Оцените статью
Adblock
detector