gpt4 book ai didi

python zeroconf 显示 IPv4 地址

转载 作者:行者123 更新时间:2023-12-03 21:22:50 27 4
gpt4 key购买 nike

我想弄清楚如何扫描网络以查找由 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 地址,您可以使用属性 address类(class)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()

关于python zeroconf 显示 IPv4 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51593574/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com