1

I am attempting to write a very simple server in python.

import socket
import sys

# Create a TCP/IP socket to listen on
server = socket.socket(socket.SOL_SOCKET, socket.SOCK_STREAM)

# Prevent from 'address already in use' upon server restart
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# Bind the socket to port 8081 on all interfaces
server_address = ('localhost', 8081)
print 'starting up on %s port %s' % server_address
server.bind(server_address)

I have read what I think to be correct documentation for the socket library, and it suggests that the server.bind() takes an argument of a tuple. However, I get this error:

starting up on localhost port 8081
Traceback (most recent call last):
  File "pyserver.py", line 14, in <module>
    server.bind(server_address)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
TypeError: argument must be string or read-only character buffer, not tuple

I have changed the argument to only a string, as the error warning suggests, and I get a

[Errno 98] Address already in use

error. I thought that the 8th line was in place to prevent that. What is going on?

user3482876
  • 249
  • 2
  • 11

1 Answers1

0

The first argument to the socket.socket should be address family:

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                       ^^^^^^^^^^^^^^

Except that, your code should work.

Reason of the error message: argument must be string ...

In Linux, the value of the socket.SOL_SOCKET is 1 which is equal to the value of socket.AF_UNIX. Unix domain socket (AF_UNIX) use path (string) as a address

>>> import socket
>>> socket.AF_UNIX
1
>>> socket.SOL_SOCKET
1

UPDATE

Regarding Already already in use error, see SO_REUSEADDR and AF_UNIX.

Community
  • 1
  • 1
falsetru
  • 357,413
  • 63
  • 732
  • 636