python zeroconf显示IPv4地址 [英] python zeroconf show IPv4 addresses

查看:323
本文介绍了python zeroconf显示IPv4地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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地址吗?

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地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆