Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python socket.gethostname

Tags:

python

sockets

I'm trying to code a small web server in python to catch an HTTP post. But I'm having an issue with the socket.gethostname part of it

here is my sample code

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversocket.bind((socket.gethostname(), 8089))
serversocket.listen(1)


while True:
    connection, address = serversocket.accept()
    buf = connection.recv(164)
    print buf

If i change

serversocket.bind((socket.gethostname(), 8089))

to

serversocket.bind(("localhost", 8089))

Everything is fine I can telnet into it, but I need to be able to connect from another web server on the internet so I need to use socket.gethostname but this block my telnet.

like image 990
Arriflex Avatar asked Dec 24 '22 07:12

Arriflex


1 Answers

You are using a clever trick to get your servers "real" address when potentially several network interfaces are open. serversocket.bind((socket.gethostname(), 8089)) can be broken down to

hostname = socket.gethostname()
dns_resolved_addr = socket.gethostbyname(hostname)
serversocket.bind((dns_resolved_addr, 8089))

You get your local hostname and then ask DNS what it thinks your IP address is, and bind to that. That's the IP address external connections will use so you should use it too.

But it doesn't always work. DNS may not know what your server name is or your server may have a different name in DNS. One example is my home network where I don't have a DNS server and the DHCP addresses handed out by my modem don't appear in a name server anywhere. A similar problem exists if your corporate DHCP doesn't register your hostname with its local DNS.

On my machine, when I go through the steps I get

>>> socket.gethostbyname(socket.gethostname())
'127.0.1.1'

Notice it was 127.0.1.1 ... I think that's some weird Ubuntu thing to keep its routing tables from getting confused. Anyway, one solution is to try to resolve the address and if you don't like it, fall back to a default.

>>> my_ip = socket.gethostbyname(socket.gethostname())
>>> if my_ip.startswith('127.0.'):
...     my_ip = '0.0.0.0'
... 
>>> my_ip
'0.0.0.0'
like image 194
tdelaney Avatar answered Dec 26 '22 22:12

tdelaney