sockets: bind to external interface

Jean-Paul Calderone calderone.jeanpaul at gmail.com
Mon Apr 25 22:13:01 CEST 2011


On Apr 25, 3:49 pm, Chris Angelico <ros... at gmail.com> wrote:
> On Tue, Apr 26, 2011 at 5:37 AM, Hans Georg Schaathun <h... at schaathun.net> wrote:
>
> > Has anyone found a simple solution that can be administered without
> > root privileges?  I mean simpler than passing the ip address
> > manually :-)
>
> You can run 'ifconfig' without being root, so there must be a way. At
> very worst, parse ifconfig's output.
>
> The way you talk of "the" external interface, I'm assuming this
> computer has only one. Is there a reason for not simply binding to
> INADDR_ANY aka 0.0.0.0? Do you specifically need to *not* bind to
> 127.0.0.1?
>
> Chris Angelico

Binding to 0.0.0.0 is usually the right thing to do.  The OP should
probably do that unless he has some particular reason for doing
otherwise.  The comment about "the standard solution of binding to
whatever socket.gethostname() returns" suggests that perhaps he wasn't
aware that actually the standard solution is to bind to 0.0.0.0.

However, the system stack can usually be tricked into revealing some
more information this way:

    >>> import socket
    >>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    >>> s.connect(('1.2.3.4', 1234))
    >>> s.getsockname()
    ('192.168.1.148', 47679)

Jean-Paul



More information about the Python-list mailing list