首页 文章

试图绑定到特定的外部ip :: [Errno 10049]请求的地址在其上下文中无效无法打开socket-(python 2.7)

提问于
浏览
0

我有一个Moxa device从串行数据创建Tcp-ip消息并通过LAN发送给我 . 我需要用python服务器听他特定的external-ip(172.16.0.77) . 我试着这样做:

BUFFER_SIZE = 10000  # Normally 1024, but we want fast response
    HOST = self.TCP_IP  #(172.16.0.77)
    PORT = self.TCP_PORT              # Arbitrary non-privileged port
    s = None
    for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                                  socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
        af, socktype, proto, canonname, sa = res
        try:
            s = socket.socket(af, socktype, proto)
        except socket.error as msg:
            print msg
            s = None
            continue
        try:
            s.bind(sa)
            s.listen(1)
        except socket.error as msg:
            print msg
            s.close()
            s = None
            continue
        break
    if s is None:
        print 'could not open socket'
    while s:
        print s.getsockname()
        conn, addr = s.accept()
        print 'Connection address:', addr
        data = conn.recv(BUFFER_SIZE)
        if data:
            self.emit(QtCore.SIGNAL("SamplesRecive"),data)
        conn.close()

我得到:[Errno 10049]请求的地址在其上下文无效无法打开套接字我需要将服务划分为许多Moxa设备所以我不能使用 socket.INADDR_ANY

有任何想法吗?

1 回答

  • 1

    socket.INADDR_ANY 等于 socket.bind('0.0.0.0')

    如果绑定到“0.0.0.0”可以监听所有接口(可用)

    Moxa TCP示例:

    import socket,time
    import thread
    
    #Example client
    class _client :
        def __init__(self):
            self.status = False
        def run(self,clientsock,addr):
            while 1 :
                try:
                    data = clientsock.recv(BUFF)
                    if data :
                        #do something with data
                        time.sleep(.1)
                        if self.status == False:
                            clientsock.close()
                            break
                        clientsock.send(next_query)
    
    
                 except Exception,e :
                    print e
                    break
    client = _client()
    ADDR = ("0.0.0.0", 45500) #so you need port how to decode raw socket data ?
    serversock = socket(AF_INET, SOCK_STREAM)
    serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serversock.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)#gain 50ms tcp delay
    serversock.bind(ADDR)
    serversock.listen(10)
    
    While True :
        clientsock, addr = serversock.accept()
        if addr[0] == device_1_IP:
            client.status = True
            #start device1 thread(moxa is TCP client mode)
            thread.start_new_thread(client.run, (clientsock, addr))
            #if client.status = False you will be close connection.
    

    But my offer is "use moxa with TCP server mode"

    我使用4x5450i 3x5250超过120设备没有任何错误 .

相关问题