pythonzeroconf 显示 IPv4 地址

python zeroconf show IPv4 addresses

我正在尝试找出如何扫描网络以查找由 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()

它有效,但它没有给我任何 IPv4 地址。 输出(示例):

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'/'})

有人可以告诉我如何获取我们网络中 avahi 发布的设备的 IPv4 地址吗?

要获取 IP 地址,您可以使用 class ServiceInfo 的属性 address。它以 bytes 类型为您提供 IP 地址(在您的 post 中显示为 b'\n\x80Cj'),因此您应该使用 socket.inet_ntoa() 将其转换为更具可读性格式。这是我在 MyListener.add_service() 方法中替换 print() 指令以打印 IP 地址的代码:

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()

您还可以直接从 ServiceInfo 获取解析后的地址。

print("Service %s added, IP address: %s" % (name, info.parsed_addresses()[0]))