Reputation: 3510
I've been working with some sockets lately, and while writing some unit test cases with a listening socket I repeatedly get error: [Errno 98] Address already in use
.
This is some example code that shows the error.
import unittest
import socket
class TestUnit(unittest.TestCase):
def setUp(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind((socket.gethostname(), 10000))
self.socket.listen(10)
self.addCleanup(self.clean)
def test_nothing(self):
self.assertEqual(False, False)
def test_something(self):
self.assertEqual(True, True)
def clean(self):
self.socket.close()
It seems to occur when one of the tests throw an exception. Without an exception it works as expected. But that kinda makes the test useless since all tests after the first that throws an exception also throw an exception.
Upvotes: 2
Views: 549
Reputation: 5535
socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
should help
Basically a closed socket is not immediately freed by the stack. Hence if you try to reuse it (even in the scenario when you have a single bind socket, but you close and restart application) immediately, you would see the same error. REUSEADDR allows binding the same socket again.
However, if your socket is in a timed wait state and you try the same destination, it would fail.
You should also read the man page for this socket option to understand it's limitations.
Upvotes: 1