3

i want to execute the following simple server code:

import socket

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 22331                # Reserve a port
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print('Got connection from', addr)
   c.send('Thank you for connecting')
   c.close() 

gives the following error while executing:

OSError: [Errno 99] Cannot assign requested address

why the OS cannot bind the specified port with the address?

Maria
  • 85
  • 1
  • 1
  • 8
  • 2
    You probably want `host = '0.0.0.0'`. `socket.gethostname()` returns the hostname, not an IP address. – Valentin Lorentz May 24 '14 at 09:04
  • I agree with @ValentinLorentz, you should try to be specific about the IP or use `0.0.0.0`. It looks like your `gethostname()` returns an IP / name that doesn't resolve to an IP address present on the host you're executing the script from. – Romuald Brunet May 24 '14 at 11:24
  • The code you mentioned in your question is not generating this error. It worked fine on Windows 8 with python v2.7. Please show us the client side code too! – ρss May 24 '14 at 11:36
  • @ValentinLorentz should it be host=IPAddress rather than host name in order to be bound? – Maria May 24 '14 at 11:58
  • @ρss i didn't run the client yet, because the server is not running/ listening. – Maria May 24 '14 at 12:01
  • @maria simply try this `host = '0.0.0.0'` and see what happens? – ρss May 24 '14 at 12:02
  • how does using hostname or 0.0.0.0 matter? – Padraic Cunningham May 24 '14 at 12:06
  • 1
    it works with giving the IP address, but not with host name – Maria May 24 '14 at 12:16
  • @maria As I mentioned before your code works fine for me even if you give a hostname or an IP. – ρss May 24 '14 at 12:17

2 Answers2

1

If it works using the ip address but not using hostname.

You should have something like this in your /etc/hosts mapping ip to hostname.

127.0.0.1   localhost
127.0.1.1   your_hostname_here

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Your /etc/hostname should obviously be the same as above.

Reboot and you should be able to ping your hostname successfully.

You can also use socket.gethostbyname(socket.gethostname()) to get the i.p as opposed to the hostname

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

Try set the SO_REUSEADDR option to the socket:

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
mitnk
  • 3,127
  • 2
  • 21
  • 28