Home > database >  How do I check if I connected to the server? Python Sockets
How do I check if I connected to the server? Python Sockets

Time:10-30

def connect_to():
print(f"[*] Connecting to {receiver_ip}:{receiver_port}")
socket.connect((receiver_ip, receiver_port))
print(f"[ ] Connected")

I haven't tested that yet, but if the connection will not be executed will this last sentence be printed? How can I check if I connected properly and make proper if statement?

CodePudding user response:

Use try except to catch the errors and if the connection is successful

CodePudding user response:

When a socket fails to connect, it will raise a socket.error exception. You can catch that specific error using some error handling techniques in Python.

import socket


def connect(ip, port):
    s = socket.socket()

    try:
        print(f"Connecting to {ip}:{port}")
        s.connect((ip, port))
    except socket.error as msg:
        print(f"Failed to connect: {msg}")
    else:
        print(f"Successfully connected to {ip}:{port}")

How can I check if I connected properly and make a proper if statement?

The except block will be executed if the specified error is caught in the try block. On the other hand, the else block will be executed when no errors were raised or handled. You can view the except block as "if error" and the else block as "if not error".

Alternatively, you can catch an error and re-raise it with your custom message.

import socket


def connect(ip, port):
    s = socket.socket()

    try:
        print(f"Connecting to {ip}:{port}")
        s.connect((ip, port))
    except socket.error as msg:
        raise socket.error(f"Failed to connect: {msg}")

    print(f"Successfully connected to {ip}:{port}")

By catching and re-raising, you don't have to use the else block anymore.

  • Related