'Address already in use' when using socket

B

Bearish

I get 'Address already in use' errors when using sockets.
Am I properly shutting down all connections? What am I doing wrong?
I've looked at the examples and I can't figure out what I'm missing.
I already read the Python Socket HOWTO at
http://py-howto.sourceforge.net/sockets/sockets.html
but I seem to be doing everything right.

Here is the server:

#! /usr/bin/python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 52340))
s.listen(1)
conn, addr = s.accept()
data = conn.recv(1024)
print "data:", data
conn.close()
s.close()
print "server closed"

Here is the client:

#! /usr/bin/python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 52340))
s.send('test string')
s.close()
print "client closed"

Here is a convenience script to run both
(although I get the same error when I run in separate shells):

#! /bin/sh
python server.py &
sleep 1
python client.py

Here is the error:

--- first time, runs just fine ---
$ source ./runboth
data: test string
server closed
client closed
[1]+ Done python server.py
--- second time (or sometimes third time), gives error ---
$ source ./runboth
Traceback (most recent call last):
File "server.py", line 4, in ?
s.bind(('localhost', 52340))
File "<string>", line 1, in bind
socket.error: (98, 'Address already in use')
[1]+ Exit 1 python server.py
Traceback (most recent call last):
File "client.py", line 4, in ?
s.connect(('localhost', 52340))
File "<string>", line 1, in connect
socket.error: (111, 'Connection refused')
 
P

Peter Hansen

Bearish said:
I get 'Address already in use' errors when using sockets.

Generally one can fix this using:

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

where "sock" is the server socket in question. Do
this prior to attempting to bind to the port.

-Peter
 
J

J Berends

Peter said:
Generally one can fix this using:

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

where "sock" is the server socket in question. Do
this prior to attempting to bind to the port.

-Peter
I agree on this, wanted to write the same thing when I saw this.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top