开发者

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? 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. I've tried '' (all network cards), '127.0.0.1', 'localhost'... all do the开发者_如何学编程 same thing.

I have also commented out the REUSEADDR part. but that made no difference either :(

BTW.. using 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?! It's almost like there is a bug in Python which is getting the two sockets confused?

Seems to work a dream now though!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜