- Getting list of network devices inside the Linux kernel
- 2 Answers 2
- How to Find What Devices are Connected to Network in Linux
- A. Using Linux command to find devices on the network
- Step 1: Install nmap
- Step 2: Get IP range of the network
- Step 3: Scan to find devices connected to your network
- B. Using GUI tool to find devices connected to network
- Просмотр компьютеров в локальной сети из терминала Linux
- 5 ответов 5
- List all MAC addresses and their associated IP addresses in my local network (LAN)
- 12 Answers 12
Getting list of network devices inside the Linux kernel
I’ve been looking through net/core/dev.c and other files to try to find out how to get the list of network devices that are currently configured and it’s proving to be a little difficult to find. The end goal is to be able to get network device statistics using dev_get_stats in dev.c, but I need to know the current interfaces so I can grab the net_device struct to pass in. I’m having to do this inside the kernel as I’m writing a module which adds in a new /proc/ entry which relates to some statistics from the current network devices so from what I can gather this must be done inside the kernel. If someone could point me to how to get the interfaces it would be much appreciated.
2 Answers 2
This ought to do the trick:
#include struct net_device *dev; read_lock(&dev_base_lock); dev = first_net_device(&init_net); while (dev) < printk(KERN_INFO "found [%s]\n", dev->name); dev = next_net_device(dev); > read_unlock(&dev_base_lock);
Given a struct net *net identifying the net namespace that you are interested in, you should grab the dev_base_lock and use for_each_netdev() :
read_lock(&dev_base_lock); for_each_netdev(net, dev) < /* Inspect dev */ >read_unlock(&dev_base_lock);
(In newer kernels, you can use RCU instead, but that is probably an overcomplication in this case).
To obtain the net namespace to use, you should be registering your proc file with register_pernet_subsys() :
static const struct file_operations foostats_seq_fops = < .owner = THIS_MODULE, .open = foostats_seq_open, .read = seq_read, .llseek = seq_lseek, .release = foostats_seq_release, >; static int foo_proc_init_net(struct net *net) < if (!proc_net_fops_create(net, "foostats", S_IRUGO, &foostats_seq_fops)) return -ENOMEM; return 0; >static void foo_proc_exit_net(struct net *net) < proc_net_remove(net, "foostats"); >static struct pernet_operations foo_proc_ops = < .init = foo_proc_init_net, .exit = foo_proc_exit_net, >; register_pernet_subsys(&foo_proc_ops)
In your foostats_seq_open() function, you take a reference on the net namespace, and drop it in the release function:
static int foostats_seq_open(struct inode *inode, struct file *file) < int err; struct net *net; err = -ENXIO; net = get_proc_net(inode); if (net == NULL) goto err_net; err = single_open(file, foostats_seq_show, net); if (err < 0) goto err_open; return 0; err_open: put_net(net); err_net: return err; >static int foostats_seq_release(struct inode *inode, struct file *file) < struct net *net = ((struct seq_file *)file->private_data)->private; put_net(net); return single_release(inode, file); >
The foostats_seq_show() function can then obtain the net , walk the devices, gather the statistics and produce the output:
static int sockstat6_seq_show(struct seq_file *seq, void *v) < struct net *net = seq->private; struct net_device *dev; int foostat, barstat; read_lock(&dev_base_lock); for_each_netdev(net, dev) < /* Inspect dev */ >read_unlock(&dev_base_lock); seq_printf(seq, "Foo: %d\n", foostat); seq_printf(seq, "Bar: %d\n", barstat); return 0; >
How to Find What Devices are Connected to Network in Linux
Wireless networks have always been a desirable target for wannabe hackers. Wireless networks are also more vulnerable to hacking than the wired ones.
Forget hacking, do you ever wonder that someone might be leeching off your hard paid wifi network? Maybe a neighbor who once connected to your network and now uses it as his/her own?
It would be nice to check what devices are on your network. This way you can also see if there are some unwanted devices on your network.
So you might end up thinking, “how do I find what devices are connected to my network”?
I’ll show you how to do that in this quick tutorial. Not only it’s a good idea from security point of view, it is also a good little exercise if you have interest in networking.
We will use both, command line and GUI, way for finding out what devices are connected to your local network in Linux. The process is very simple and easy to use even for beginners.
Before you see any of that, let me tell you that your router should also be able to show all the connected devices. Check your gateway ip address and then type it in a browser. This is usually the browser interface for your router. Enter the username and password and you can see all the details and devices connected to the router.
If you don’t remember the router password or you don’t want to go that way, here’s what else you could do.
A. Using Linux command to find devices on the network
Step 1: Install nmap
nmap is one of the most popular network scanning tool in Linux. Use the following command to install nmap in Ubuntu based Linux distributions:
You can easily install it in other Linux distributions as well. It should be in the official software repository.
Step 2: Get IP range of the network
Now we need to know the IP address range of the network. Use the ifconfig command to find the IP address in Linux. Look for wlan0 if you are using wifi or eth0 if you are using Ethernet.
[email protected]:~$ ifconfig
wlan0 Link encap:Ethernet HWaddr 70:f1:a1:c2:f2:e9
inet addr:192.168.1.91 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::73f1:a1ef:fec2:f2e8/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:2135051 errors:0 dropped:0 overruns:0 frame:0
TX packets:2013773 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1434994913 (1.4 GB) TX bytes:636207445 (636.2 MB)
The important things are highlighted in bold. As you see my IP is 192.168.1.91 and the subnet mask is 255.255.255.0 which means that the ip address range on my network varies from 192.168.1.0 to 192.168.1.255.
You may also use ip a command to know your IP address in Ubuntu and other Linux distributions.
At the same time, I’ll recommend you to read about basic Linux networking commands for more information.
Step 3: Scan to find devices connected to your network
It is advisable to use root privileges while scanning the network for more accurate information. Use the nmap command in the following way:
[email protected]:~$ sudo nmap -sn 192.168.1.0/24
Starting Nmap 5.21 ( http://nmap.org ) at 2012-09-01 21:59 CEST
Nmap scan report for neufbox (192.168.1.1)
Host is up (0.012s latency).
MAC Address: E0:A1:D5:72:5A:5C (Unknown)
Nmap scan report for takshak-bambi (192.168.1.91)
Host is up.
Nmap scan report for android-95b23f67te05e1c8 (192.168.1.93)
Host is up (0.36s latency).
As you can see that there are three devices connected to my network. The router itself, my laptop and my Galaxy S2.
If you are wondering about why I used 24 in the above command, you should know a little about CIDR notation. It basically means that the scanning will be from 192.168.1.0 to 192.168.1.255.
B. Using GUI tool to find devices connected to network
When I first wrote this article, there was no GUI tool for this task. Then I came across a new network monitoring tool being developed for elementary OS. I suggested including a periodic device scan feature in this tool and the developer readily agreed.
So, now we have a GUI tool that does this task. It’s called Nutty (last updated in 2019). Just install this app and run it. It will periodically scan for new devices on the network and will notify you if there is a new device.
This application is only available for elementary OS, Ubuntu and hopefully, other Ubuntu based Linux distributions. You can find installation instructions on this detailed article on Nutty.
Oh, you can also log in to your router and see the devices connected to your devices. I let you figure the best way to find devices connected to your network.
Просмотр компьютеров в локальной сети из терминала Linux
Полный чайник в Linux. Как посмотреть из терминала все компьютеры, которые подключены к локальной сети ? Поясню подробней. Интернет-кабель у меня подключен к роутеру. От роутера идет несколько кабелей к компьютерам с Ubuntu. А теперь сам вопрос. Как мне с одного из этих компьютеров увидеть остальные компьютеры внутри сети роутера ?
А с какой целью интересуетесь ? Т.е. что вы понимаете под «компьютером подключенным к локальной сети». Вам их ip/mac адресов достаточно или вы ждете чего то большего
5 ответов 5
Не совсем понятно что имеется в виду, но предложу варианты (маску подставить по необходимости):
- nmap -sn 192.168.0.0/24 (при блокировке ICMP файрволом можно попробовать другие варианты, например, UDP: nmap -sn -PU 192.168.0.0/24 )
- echo 192.168.0.|xargs -n1 -P0 ping -c1|grep «bytes from» (это те, кто на пинг отвечает)
Для начала убедитесь, что установлена samba. Если такой пакет присутствует и задана рабочая группа, выполните в консоли
samba должна стоять на компьютере, с которого идет поиск. На разыскиваемых можно посмотреть, отктрыт ли порт 139 tcp.
Сканируйте сеть, проверяйте открыт ли порт. Я привел в ответе вариант для обычной одноранговой сети. Должно работать как в windows (компьютеры сети)
Есть очень удобная утилитка fping http://fping.org/ Прямо-таки для этого создана. Можно nmap , но это будет гораздо медленнее.
Как и nmblookup он требует, чтобы на компьютерах была установлена соответствующая служба, для linux это avahi-daemon . (С нашими тупыми провайдерами рекомендую всегда отключать проверку на использование домена .local: в /etc/default/avahi-daemon поставить AVAHI_DAEMON_DETECT_LOCAL=0 )
Чтобы компьютер с linux отвечал на это, нужно сделать на нём:
# sysctl net.ipv4.icmp_echo_ignore_broadcasts=0
Некоторые маршрутизаторы это так же поддерживают.
Ну и более низкоуровневый и как мне кажется более надёжный для односегментной сети:
$ echo 192.168.2. | xargs -n1 -P0 arping -c 4 -f -I eth0 | grep "reply from"
List all MAC addresses and their associated IP addresses in my local network (LAN)
How can I list all MAC addresses and their associated IP addresses of the machines connected to my local network (LAN)?
it’s important to understand that as soon as you go throught a level 3 network layer equipement it will not be possible to get the MAC and ip behind this equipement
sudo tail -f /var/log/messages , then unplug and replug in the device you’re trying to find the MAC address of, or grep/read through messages to find the device.
12 Answers 12
You can use the Nmap utility for this. Nmap is a free network scanner utility.
Please substitute your network identifier and subnet mask.
How to find a network ID and subnet mask
bash~$ ip a 1: lo: mtu 65536 qdisc noqueue state UNKNOWN link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: wlan0: mtu 1500 qdisc mq state UP qlen 1000 link/ether c4:85:08:94:ee:9a brd ff:ff:ff:ff:ff:ff inet 192.168.3.66/24 brd 192.168.3.255 scope global wlan0 inet6 fe80::c685:8ff:fe94:ee9a/64 scope link valid_lft forever preferred_lft forever
Here at point 2, I have the wlan0 device. It says inet 192.168.3.66/24 brd 192.168.3.255 scope global wlan0 , IP address: 192.168.3.66 , subnet mask: 24 . Network ID is 192.168.3.0 , just substitute the last number by 0.
Here is a little quote from the man page, nmap(1):
This option tells Nmap not to do a port scan after host discovery, and only print out the available hosts that responded to the scan. This is often known as a “ping scan”, but you can also request that traceroute and NSE host scripts be run. This is by default one step more intrusive than the list scan, and can often be used for the same purposes. It allows light reconnaissance of a target network without attracting much attention. Knowing how many hosts are up is more valuable to attackers than the list provided by a list scan of every single IP address and host name.
Systems administrators often find this option valuable as well. It can easily be used to count available machines on a network or monitor server availability. This is often called a ping sweep, and is more reliable than pinging the broadcast address because many hosts do not reply to broadcast queries.
The default host discovery done with -sn consists of an ICMP echo request, TCP SYN to port 443, TCP ACK to port 80, and an ICMP timestamp request by default. When executed by an unprivileged user, only SYN packets are sent (using a connect call) to ports 80 and 443 on the target. When a privileged user tries to scan targets on a local Ethernet network, ARP requests are used unless —send-ip was specified. The -sn option can be combined with any of the discovery probe types (the -P* options, excluding -Pn ) for greater flexibility. If any of those probe type and port number options are used, the default probes are overridden. When strict firewalls are in place between the source host running Nmap and the target network, using those advanced techniques is recommended. Otherwise hosts could be missed when the firewall drops probes or their responses.
In previous releases of Nmap, -sn was known as -sP .