views:

52

answers:

3

I used python's socket module and tried to open a listening socket using

import socket
import sys

def getServerSocket(host, port):
    for r in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                                socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
        af, socktype, proto, canonname, sa = r
        try:
            s = socket.socket(af, socktype, proto)
        except socket.error, msg:
            s = None
            continue
        try:
            s.bind(sa)
            s.listen(1)
        except socket.error, msg:
            s.close()
            s = None
            continue
        break
    if s is None:
        print 'could not open socket'
        sys.exit(1)
    return s

Where host was None and port was 15000.

The program would then accept connections, but only from connections on the same machine. What do I have to do to accept connections from the internet?

+4  A: 

Try 0.0.0.0. That's what's mostly used.

Ikke
+1  A: 

You'll need to bind to your public IP address, or "all" addresses (usually denoted by "0.0.0.0").

If you're trying to access it across a network you also might need to take into account firewalls etc.

Brenton Alker
How would I do that? I know that both computers are behind different wireless routers.
Joshua Moore
Difficult to answer. Try it first (it might not be a problem), but you'll need to find how to configure each of the devices involved. Usually only the "server" side will need any special attention, as outgoing packets aren't usually filtered by default. But serverfault might be a better place to get answers on that.
Brenton Alker
+4  A: 

The first problem is that your except blocks are swallowing errors with no reports being made. The second problem is that you are trying to bind to a specific interface, rather than INADDR_ANY. You are probably binding to "localhost" which will only accept connections from the local machine.

INADDR_ANY is also known as the constant 0x00000000, but the macro is more meaningful.

Assuming you are using IPv4 (that is, "regular internet" these days), copy the socket/bind code from the first example on the socket module page.

msw
http://docs.python.org/library/socket.html#socket.getaddrinfo doesn't say anything about an interface.Would socket.INADDR_ANY replace socket.AF_UNSPEC or socket.SOCK_STREAM?
Joshua Moore
The interface is implied by the address you bind to, in your case, that would be the variable `sa`. Quoth that manual page: "For IPv4 addresses, two special forms are accepted instead of a host address: the empty string represents INADDR_ANY...". The call to `getaddrinfo` will return a list of addresses, none of which are INADDR_ANY.
msw