python zeroconf show IPv4 addresses

旧街凉风 提交于 2020-05-15 05:54:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!