简体   繁体   中英

Detect if Android phones are connected to LAN

Hi guys i'm writing a smart home extension for my Raspberry Pi home server. For this i want to know when anybody is at home by checking if a smartphone is connected to the local network.

Unfortunately pinging Android devices was in the best cases unreliable so far. It depends on the sleep state and the Nexus 5X is not responding to pings at all. I also don't to to fiddle around the the sleep settings since that will decrease the battery life.

My router says the devices are connected but i don't know how to relay this information. Is there any way i can know for sure any smartphone is connected to the WiFi with Python?

I believe this question has been asked before but it took me some Googling to find it. The short answer is yes, but it will require some knowledge of your router's services, DNS and DHCP.

Okay, the easy way is to use the 'python-nmap' module which maps the function.

import nmap
nm = nmap.PortScanner()
nm.scan(hosts='192.168.0.1/24', arguments='-n -sP -PE -PA21,23,80,3389')
hosts_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()]
for host, status in hosts_list:
     print('{0}:{1}'.format(host, status))

Where '192.168.0.1' is your router IP. This returns a list of all connected devices, including any sleeping Android devices.

192.168.178.1:up
192.168.178.2:up
...

Unfortunately this python-nmap does not use Python3 which is something i still have to figure out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM