Linux все компьютеры сети

How can I list all IPs in the connected network, through Terminal preferably?

Using Ubuntu 10.10 command line, how can I list all IPs connected to my home network? Ideally, it needs to be a CLI command as I will be running it from C++.

10 Answers 10

Check out the arp-scan command — you will probably have to install it eg:

sudo apt-get install arp-scan 

And to give further detail:

sudo arp-scan --interface=eth0 --localnet 

Where eth0 is your device. You can find your device with:

Works perfectly on OSX too! Installed with Brew, and interface was en0, rather than eth0, but works great.

It’s worth noting that this does not use the ARP cache: it performs an actual scan. Unlike most nmap scans, this cannot cross layer 3 boundaries, which is usually what you want in this scenario. (In other words, it’s limited to your subnet.)

Use nmap. example: nmap -sn 10.10.10.0/24 The arp cache will only tell you those that you have tried to contact recently.

@kolonel That’s just an example. You should substitute it with your network. The 24 is «slash notation» of the subnet mask. It means use 24 bits from the left. It’s equivalent to 255.255.255.0.

@Keith do you know how I’d find out my network address to use? Or is it just my IP with 0/24 at the end?

He is right. «arp» only shows ip addresses which we tried to contact recently. I cleared arp cache and again listed «arp -a» and found nothing. If in case anyone want to clear arp cache use this command » ip -s -s neigh flush all «.

In windows this would be arp -a an equivalent of that in Linux would be arp -e .

From the man page for arp :

arp with no mode specifier will print the current content of the table. -e : Use default Linux style output format (with fixed columns). 

That looks like it works (may need to have a play as I am on a public network so it only seems to list all the servers on the network.

That command will only list the devices in the hosts current arp cache and that will only be the ones which the host has contacted recently.

Both work on Linux, but arp -a displays (all) hosts in alternative (BSD) style. Simpy running arp does the same as running arp -e beacuse that’s the default.

If your network is 192.168.0.0/24 , make an executable file with the following code; Change the 192.168.0 to your actual network.

#!/bin/bash for ip in 192.168.0.; do ping -c 1 -W 1 $ip | grep "64 bytes" & done 

Hi Anders. The user’s network might not be 192.168.0.0/24; I made a note. The site’s formatting did not like a bare #!, and so clobbered the formatting of the code snippet: when entering code, use the blockquote or preformatted text buttons, and review your answer for proper formatting before submitting it, as carriage returns, tabs, and spaces might have been stripped.

Читайте также:  Reading logs in linux

As well, when supplying a script that needs to be put into a file and made executable, rather than simply cut & pasted, it’s probably best that you specify this; it may not be obvious to some what all is required to implement your solution.

Technically, this will only return hosts that respond to ping. There may be hosts that are connected, but not replying to ICMP echo requests. As well, one can broadcast one packet to an entire network by specifying the broadcast address, which is the last address in the IP network: ping -c 1 -W 1 192.168.0.255 would accomplish the same as the for loop.

@NevinWilliams (required -b, removed -W to wait more) ping -b -c 1 192.168.0.255 result «1 packets transmitted, 0 received, 100% packet loss, time 0ms»

Try installing nmap ( sudo apt-get install nmap ) and type nmap 192.168.1.0/24 substituting 192.168.1 with the first three parts of your ip address (find out using ip addr ).

You can also get a slightly less accurate (in my experience) map of a network by running ping 192.168.1.255 (again substituting 192.168.1 ), which should issue a ping to every machine on the network, but, in my experience, does not always function correctly.

Actually, none of the answers will always work correctly. IP wasn’t designed with this requirement in mind, and there are things like Private VLANs which make it impossible to find any other hosts on the same LAN.

For a more compact list of connected devices:

nmap -sL 192.168.0.* will list all IPs in subnetwork and mark those, that have name:

Nmap scan report for 192.168.0.0 Nmap scan report for Dlink-Router.Dlink (192.168.0.1) Nmap scan report for 192.168.0.2 . Nmap scan report for android-473e80f183648322.Dlink (192.168.0.53) . Nmap scan report for 192.168.0.255 

As all interesting records start with parenthesis ( and digit 1 , we filter for that with | grep \(1 (backslash is needed to escape parenthesis)

Quirk
Beware that if two devices have the same name, nmap will show only the one, that was connected to router last

If the you have the exact same answer for two questions then it may be worth considering flagging the questions as duplicate rather than posting duplicate answers. That way knowledge can be shared as similar questions get linked together.

@Mokubai You are right, I’ve add comment to the OP. This shows an interesting problem. A quick search discovered 6 duplicates (this Q and 5 links) across 4 network sites (SU, Ask Ubuntu, SF, Unix). Sure there are much more! How do I handle this ? Ideally, each of these 6 posts should link to 5 others. Adding all these links by hand clearly doesn’t scale. So, for now I’ve linked to this post (most upvoted). Another problem is that it’s impossible to mark Q on AskUbuntu as a duplicate of the Q on SU. Hm. Probably, this was already discussed on the meta ?

doesn’t work for me on Centos 7, just lists every possible IP address in the network with no names. arp-scan worked for me.

Came up with the following on a nexus using tmux as arp-scan isn’t in the repo but nmap came pre-installed, displays just the ip addresses:

nmap -sn 192.168.1.1-254/24 | egrep "scan report" | awk '' 

Ellaborating on Anders Larrson’s answer —

#!/bin/bash function scan () < for ip in $1.; do ping -c 1 -W 1 $ip & done | sed -nE 's:^.* from ([0-9.]+).*time=(.*s)$:\1 (\2):p' > if [ $1 ]; then for baseip; do scan $baseip done else scan 192.168.1 fi 

This Answer determines the subnet by itself while in the other answers you need to provide it.

Читайте также:  Oracle linux http server

The script uses arp -a or ip -o -f inet addr show to find the subnet.

I’ve build the script elaborating on @anders-larsson and @mathieu-caroff ‘s answers. I avoid the use of ‘nmap’, but the script is easily amended to use nmap.

Basically, $baseip is built using bash replacement macros in the second part of the script if no parameter is provided on the command line. Otherwise it will scan the provided subnet (style: 192.1.5 without the third dot last byte of the IP).

#!/bin/bash function scan () < for ip in $1.; do ping -c 1 -W 1 $ip & done | sed -nE 's:^.* from ([0-9.]+).*time=(.*s)$:\1 (\2):p' wait > if [ $1 ]; then for baseip; do scan $baseip done else baseip=$(arp -a) && baseip=$ && baseip=$ if [ $baseip"" == "" ] ; then baseip=$(ip -o -f inet addr show|grep "scope global") && baseip=$ && baseip=$ fi baseip=$ scan $baseip fi 

Источник

Просмотр компьютеров в локальной сети из терминала Linux

Полный чайник в Linux. Как посмотреть из терминала все компьютеры, которые подключены к локальной сети ? Поясню подробней. Интернет-кабель у меня подключен к роутеру. От роутера идет несколько кабелей к компьютерам с Ubuntu. А теперь сам вопрос. Как мне с одного из этих компьютеров увидеть остальные компьютеры внутри сети роутера ?

А с какой целью интересуетесь ? Т.е. что вы понимаете под «компьютером подключенным к локальной сети». Вам их ip/mac адресов достаточно или вы ждете чего то большего

5 ответов 5

Не совсем понятно что имеется в виду, но предложу варианты (маску подставить по необходимости):

  1. nmap -sn 192.168.0.0/24 (при блокировке ICMP файрволом можно попробовать другие варианты, например, UDP: nmap -sn -PU 192.168.0.0/24 )
  2. 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" 

Источник

How to see all computers connected to a network

I am in a LAN and there are 3 Ubuntu, 2 Kubuntu, 2 Windows XP and 2 Windows 7. What commands or tools are available to see what PCs are connected to the LAN that it shows the name of the PC and the IP. Similar to tools like Angry IP that show all PCs in a LAN. Note that I do not know the IPs or names of the computers connected to the LAN. So the tool or command should look for them to.

Читайте также:  Linux nginx postgresql python

9 Answers 9

Arp-scan works great for me too.

sudo arp-scan -l --interface=wlan0 
sudo arp-scan -l --interface=eth0 

(this last is practically identical to what Rajesh Rajendran posted; the -l standing for —localnet)

If you don’t have arp-scan (it doesn’t come with Ubuntu by default), just pull up a terminal and type:

sudo apt-get install arp-scan 

If this doesn’t work use ifconfig to get a list of interfaces and try switching eth0 to something else.

It’s not showing any IPs for me. sudo arp-scan -l —interface=wlp4s0 Interface: wlp4s0, datalink type: EN10MB (Ethernet) Starting arp-scan 1.9.5 with 256 hosts 14 packets received by filter, 0 packets dropped by kernel Ending arp-scan 1.9.5: 256 hosts scanned in 1.975 seconds (129.62 hosts/sec). 0 responded

for ip in $(seq 1 254); do ping -c 1 192.168.1.$ip>/dev/null; [ $? -eq 0 ] && echo "192.168.1.$ip UP" || : ; done 

But for a great tool, Nmap. Great for mapping networks.

I always use nmap. To scan for all devices in your network, use:

It is a great tool to know about. You may want to install nmap using:

sudo apt-get install nmap if you are using Debian or

sudo pacman -S nmap if you are using Arch.

As a possible GUI option, the best one I have seen is Angry IP as found in http://angryip.org/download/#linux

Simply download the latest DEB package and install. Then run ipscan from Dash. Here is a screenshot:

enter image description here

it is really good, I added all fetchers to the list columns, what helped most were hostname and macvendor, now everything connected to my wifi is more understandable, thx!

@JeffWard menu: tools/fetchers//availableFetchers//»lastItemOnTheList», then sort by macvendor, it is a short name of the hardware like D-Link

arp

Address HWtype HWaddress Flags Mask Iface iPhone-von-me.fritz.box ether 12:55:05:30:3c:df C wlp3s0 android-abcdefghijklmno ether 11:66:3f:71:04:d6 C wlp3s0 fritz.box ether 00:11:3f:46:37:c2 C wlp3s0 Blupiblu.fritz.box ether 71:88:cc:bb:dc:a6 C wlp3s0 

ip neigh

ip neigh and hosts . NO nmap / sudo required.

Building on this, you can build a Python script:

#!/usr/bin/env python """List all hosts with their IP adress of the current network.""" import os out = os.popen('ip neigh').read().splitlines() for i, line in enumerate(out, start=1): ip = line.split(' ')[0] h = os.popen('host <>'.format(ip)).read() hostname = h.split(' ')[-1] print("3>: <> (<>)".format(i, hostname.strip(), ip)) 
wget https://gist.githubusercontent.com/MartinThoma/699ae445b8a08b5afd16f7d6f5e5d0f8/raw/577fc32b57a7f9e66fdc9be60e7e498bbec7951a/neighbors.py 

If broadcast isn’t disabled on your router.

You can ping the broadcast address.

Will broadcast the ping command to every host within the 192.168.0/24 subnet.

Note: It’s probably a good idea to keep broadcasting turned off though as that’s how hackers can exploit a network using a DDOS Smurf attack. Basically, ping the broadcast address with a packet that has a spoofed destination address (ie the ip address of the victim). There’s a little more to it than that but that’s what Google is for.

Note: The same also works on Windows but you ping the actual broadcast address (not the subnet).

Источник

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