问题描述
我正在尝试找出如何扫描网络以查找avahi发布的设备.
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()
它可以工作,但是没有给我任何IPv4地址.输出(示例):
It works, but it doesn't give me ANY IPv4 address.Output(example):
请问有人告诉我如何获取avahi在我们的网络中发布的设备的IPv4地址吗?
Could PLEASE someone tell me how to get the IPv4 Addresses of the devices which are published by avahi in our network?
推荐答案
要获取IP地址,可以使用类ServiceInfo
的属性address
.它为您提供bytes
类型的IP地址(在您的帖子中,它显示为b'\n\x80Cj'
),因此您应该使用socket.inet_ntoa()
将其转换为更具可读性的格式.这是我替换MyListener.add_service()
方法中的print()
指令以打印IP地址的代码:
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()
这篇关于python zeroconf显示IPv4地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!