Resolving NoneType.__format__ Error in a Python UDP Ping Function

39 Views Asked by At

I am currently working on a script to perform a UDP ping to a server and calculate the response times. It should be sending a UDP packet and await for a response, measuring the round-trip time. However, I'm encountering an error when the response time is None, specifically when trying to format it for printing. Here's the relevant part of my code:

def udp_ping(ip, port):
    """
    Sends a UDP packet to the specified IP and port, measures the round-trip time,
    and returns the response time in milliseconds and any error messages.
    """
    try:
        # Creating a UDP socket
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
            sock.settimeout(5)  # Set timeout for the entire operation

            # Send a simple message
            start_time = time.time()  # Record start time
            sock.sendto(b"Ping", (ip, port))  # Sending a "Ping" message

            try:
                # Attempt to receive a response
                data, addr = sock.recvfrom(1024)  # Buffer size of 1024 bytes
                end_time = time.time()  # Record end time

                # Calculate response time in milliseconds
                ms_response = (end_time - start_time) * 1000
                return ms_response, None  # Return response time and no error
            except socket.timeout:
                # Handle case where response is not received in time
                return None, "Connection timeout"
    except Exception as e:
        # Handle any other exceptions that may occur
        return None, f"Error: {str(e)}"

# Example usage of the function
response_time, error = udp_ping('example.com', 80)

if response_time is not None:
    print(f"Response time: {response_time} ms")
elif error:
    print(f"An error occurred: {error}")
else:
    print("No response received or an unknown error occurred.")

And the error I keep getting is:

Attempting to connect to IP [IP] on UDP Port: 53

An error occurred | Error: unsupported format string passed to NoneType.__format__

It is occurring when the function returns None for the response_time and the calling code attempts to format this None value. And I have tried checking if response_time is None before formatting but the issue remains. Can anyone help me identify what I'm missing or suggest a better way to handle this?

0

There are 0 best solutions below