加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – ZeroMQ如何在pyzmq中获取绑定地址

发布时间:2020-12-20 13:26:59 所属栏目:Python 来源:网络整理
导读:我在 Python中使用ZMQ绑定,我想将客户端绑定到某个端口,然后将该位置发送到其他客户端进行连接. 现在这是基本的绑定代码: subscriber = context.socket(zmq.SUB)...subscriber.bind("tcp://0.0.0.0:12345") 我需要得到的是外部地址,而不是0.0.0.0,假设我的
我在 Python中使用ZMQ绑定,我想将客户端绑定到某个端口,然后将该位置发送到其他客户端进行连接.
现在这是基本的绑定代码:

subscriber = context.socket(zmq.SUB)
...
subscriber.bind("tcp://0.0.0.0:12345")

我需要得到的是外部地址,而不是0.0.0.0,假设我的电脑有IP 192.168.1.10,我需要得到“tcp://192.168.1.10:12345”并将其发送给其他客户端,因为发送tcp: //0.0.0.0:12345没用.

如何获取ZMQ用于创建套接字的外部IP接口?

在PC上可以有多少个NIC,如果我只是尝试使用普通套接字获取外部IP,它可能无效,因为我不知道NIC ZMQ使用了什么.

解决方法

0.0.0.0(INADDR_ANY)是“任意”地址(不可路由的元地址).这是一种指定“任何IPv4接口”的方法.
这意味着您的所有接口都在侦听端口12345.

要列出所有网络接口,我建议使用像this这样的库

如果你使用的是linux,你可以这样做:

import array
import struct
import socket
import fcntl

SIOCGIFCONF = 0x8912  #define SIOCGIFCONF
BYTES = 4096          # Simply define the byte size

# get_iface_list function definition 
# this function will return array of all 'up' interfaces 
def get_iface_list():
    # create the socket object to get the interface list
    sck = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

    # prepare the struct variable
    names = array.array('B','' * BYTES)

    # the trick is to get the list from ioctl
    bytelen = struct.unpack('iL',fcntl.ioctl(sck.fileno(),SIOCGIFCONF,struct.pack('iL',BYTES,names.buffer_info()[0])))[0]

    # convert it to string
    namestr = names.tostring()

    # return the interfaces as array
    return [namestr[i:i+32].split('',1)[0] for i in range(0,bytelen,32)]

# now,use the function to get the 'up' interfaces array
ifaces = get_iface_list()

# well,what to do? print it out maybe... 
for iface in ifaces:
 print iface

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读