1

Is there a way to detect whether a socket.socket instance passed to a function that already has the connection setup is a server-side socket (Executed socket.accept()) or is a client-side socket (Executed socket.connect().

Basically I'm looking for something to check about the socket to implement is_server_socket being used below:

def func(sock):
    if is_server_socket(sock):
        print("I'm a server!")
    else:
        print("I'm a client!")
2
  • 1
    If you are using UDP, there is no concept of server or client sockets. If you are using TCP, you should probably check the logic of your code, because having a function that takes either a server or a client socket but makes a distinction between the two makes little sense. Commented Dec 26, 2016 at 21:57
  • @ValentinLorentz It's TCP only. The interface I'm creating uses "stream IDs" similar to how HTTP/2 does it, and to avoid stream ID overlap forces the client or server instance to be either odd or even stream IDs. My interface knows nothing of external code, only the socket passed to it. Please don't question my question. Instead, focus your efforts on finding an answer if there is one. Commented Dec 26, 2016 at 21:59

1 Answer 1

2

A connected socket has a peer while a socket which is not connected does not have a peer. Thus you can use getpeername to distinguish between connected and not connected socket.

Note that not every socket which is not connected is a server socket. It might simply be a socket which is not connected yet (i.e. socket created but connect not called). But if you need to only distinguish between a socket which you can call accept on and a socket which you got as the result of accept than getpeername is enough. Still, it would be better to keep this information in a local variable instead of calling getpeername all the time since this is a system call and thus comparably expensive.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.