Niels B.
Niels B.

Reputation: 6310

Detect if `connect()` has been invoked on TCP socket

If feel this should be incredibly obvious, but somehow I haven't found it in the documentation: https://docs.python.org/3/library/socket.html

Consider this

import socket
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

How do I check if connect() has been called on my_socket. Currently my code sets a separate boolean in my class, but I believe it should be possible to ask the socket object about that. For clarification, I am writing client code and I want to provide some introspection in my classes to check if the socket has been connected to a server.

Something like

my_socket.is_connected()
=> False
my_socket.connect(("127.0.0.1", 42))
=> None
my_socket.is_connected()
=> True

Upvotes: 2

Views: 195

Answers (2)

ForceBru
ForceBru

Reputation: 44830

If you want to detect if connect has been called, you can just subclass socket.socket like this:

class Sock(socket.socket):
    def connect(self, *args, **kwargs):
        super().connect(*args, **kwargs)
        print("tried to connect!")

And then use Sock just like you'd use socket.socket:

my_socket = Sock(socket.AF_INET, socket.SOCK_STREAM)

Upvotes: 2

user207421
user207421

Reputation: 310840

Try to call getpeername() and handle the resulting error or state if it isn't connected.

Upvotes: 3

Related Questions