问题
I'm trying to figure out how to scan the network for devices which are published by avahi.
#!/usr/bin/python3
from zeroconf import ServiceBrowser, Zeroconf
from time import sleep
class MyListener:
def remove_service(self, zeroconf, type, name):
print("Service % removed" % (name))
def add_service(self, zeroconf, type, name):
info = zeroconf.get_service_info(type, name)
info = str(info)
info = info.split(",")[6]
print(info)
zeroconf = Zeroconf()
listener = MyListener()
browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener)
try:
sleep(1)
finally:
zeroconf.close()
It works, but it doesn't give me ANY IPv4 address. Output(example):
ServiceInfo(type='_http._tcp.local.', name='Barco ptp-owsserver-2237._http._tcp.local.', address=b'\n\x80Cj', port=80, weight=0, priority=0, server='ptp-owsserver-2237.local.', properties={b'root': b'/'})
Could PLEASE someone tell me how to get the IPv4 Addresses of the devices which are published by avahi in our network?
回答1:
To get the IP addresses, you can use the attribute address
of class ServiceInfo
. It gives you the IP address in bytes
type (in your post, it is displayed as b'\n\x80Cj'
), so that you should use socket.inet_ntoa()
to convert it to a more readable format. Here is the code where I replaced the print()
instruction in the MyListener.add_service()
method in order to print the IP address:
from zeroconf import ServiceBrowser, Zeroconf
import socket
class MyListener:
def remove_service(self, zeroconf, type, name):
print("Service %s removed" % (name,))
def add_service(self, zeroconf, type, name):
info = zeroconf.get_service_info(type, name)
if info:
#print("Service %s added, service info: %s" % (name, info))
print("Service %s added, IP address: %s" % (name, socket.inet_ntoa(info.address)))
zeroconf = Zeroconf()
listener = MyListener()
browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener)
try:
input("Press enter to exit...\n\n")
finally:
zeroconf.close()
来源:https://stackoverflow.com/questions/51593574/python-zeroconf-show-ipv4-addresses