简体   繁体   English

Python 套接字代理示例,调用 bind() 时不断出错。为什么?

[英]Python socket proxy example, keep getting errors calling bind().. why?

I'm writing an ad-hoc proxy that takes commands from a fifo file, then hosts arbitary proxy connections using python socket and select.poll.. My problem is that very frequently, when calling socket.bind.. I get either a "Bad file descriptor" error, or a "Socket operation on non-socket", and I'm not sure why?我正在编写一个 ad-hoc 代理,它从 fifo 文件中获取命令,然后使用 python 套接字和 select.poll 托管任意代理连接。我的问题是,在调用 socket.bind 时非常频繁。我得到一个“错误的文件描述符”错误,或“非套接字上的套接字操作”,我不知道为什么? Here is a snippet of the code:这是代码片段:

pull_sock=socket.socket()
push_sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
pull_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
push_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
clients={}
# start pull connection
try:
    print "connecting to:", saddr, sport
    pull_sock.connect((saddr,sport))
    except Exception, e:
        print "unable to connect:", repr(e)
        self._threadsafe_remove_dport(dport)
        return
    # start push server connection
    try:
        sleep(1)
        push_sock.bind(('',dport))
        push_sock.listen(1)
        print "host new proxy on %d to %s:%d" % (dport, saddr, sport)
        print "pushfd=",push_sock.fileno(),"pullfd=",pull_sock.fileno()
        # register sockets for async polling
        sockpoll = select.poll()
        sockpoll.register(push_sock, select.POLLIN | select.POLLOUT)
        sockpoll.register(pull_sock, select.POLLIN)

It's the bind() command that always fails, nothing else.总是失败的是bind()命令,仅此而已。 I've tried '' (all network cards), '127.0.0.1', 'localhost'... all do the same thing.我试过''(所有网卡),'127.0.0.1','localhost'......都做同样的事情。

I have also commented out the REUSEADDR part.我还注释掉了REUSEADDR部分。 but that made no difference either:(但这也没有什么区别:(

BTW.. using Arch Linux顺便说一句..使用Arch Linux

Hmmm.... If I declare the push_sock varaible after the pull_sock.connect bits and just before the bind, it no longer happens??嗯....如果我在pull_sock.connect之后和绑定之前声明 push_sock 变量,它不再发生? It's almost like there is a bug in Python which is getting the two sockets confused?几乎就像 Python 中存在一个错误,这让两个 sockets 混淆了?

Seems to work a dream now though!不过现在似乎在做一个梦!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM