2012-03-11 10 views
3

私はPython用のzmqバインディングを使用しています。クライアントをいくつかのポートにバインドして、その場所を他のクライアントに送信して接続します。 は今、これは基本的なバインディングコードです:私は取得する必要がどのような0mqバインドされたアドレスを取得する方法

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

外部アドレスではない0.0.0.0です。私のPCはip 192.168.1.10を持っているとしましょう。 "tcp://192.168.1.10:12345"を取得して他のクライアントに送信する必要があります。 "tcp://0.0.0.0:12345"を送信することは役に立たないからです。 zmqがソケットの作成に使用したインタフェースの外部IPを取得するにはどうしたらいいですか?私はNIC zmqが何を使用していたのかわからないので、通常のソケットを使って外部IPを取得しようとすると無効になる可能性があります。

答えて

1

0.0.0.0(INADDR_ANY)は、「任意の」アドレス(ルーティング不可能なメタアドレス)です。これは、「すべてのIPv4インタフェースを指定する」方法です。 これは、すべてのインタフェースが、私はあなたがこれを行うことがLinuxを使用している場合はthis

のようなライブラリを使用することをお勧めしますすべてのネットワークインターフェイスを一覧表示するには、ポート12345

に聞いていることを意味します

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 
関連する問題