python zeroconf显示IPv4地址

时间:2018-07-30 12:04:01

标签: python ipv4 zeroconf

我正在尝试找出如何扫描网络以查找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。',地址= b'\ n \ x80Cj',端口= 80,   权重= 0,优先级= 0,服务器='ptp-owsserver-2237.local。',   properties = {b'root':b'/'})

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

2 个答案:

答案 0 :(得分:1)

要获取IP地址,可以使用类address的属性ServiceInfo。它为您提供bytes类型的IP地址(在您的帖子中显示为b'\n\x80Cj'),因此您应该使用socket.inet_ntoa()将其转换为更易读的格式。这是我在print()方法中替换MyListener.add_service()指令以打印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()

答案 1 :(得分:0)

您也可以直接从 ServiceInfo 获取解析地址。

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