2012-03-11 67 views
3

我使用zmq綁定python,我想綁定客戶端到某個端口,然後將該位置發送到其他客戶端進行連接。 現在,這是基本的綁定代碼:0mq如何獲得綁定地址

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,它可能是無效的,因爲我不知道zmq使用了什麼網卡。

回答

1

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', '\0' * 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('\0', 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