Hai Hoang
Hai Hoang

Reputation: 1257

Python socket bind reports port already in used but socket connect_ex return 0

I am finding a way to check if a port is already in use using python. Some answers to the same question suggested use connect_ex and check the returned code. If the returned code is 0, that mean the port is not occupied by other process.

But my problem is connect_ex return 0 but bind throw an exception saying the port is in used.

import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    print("test using connect_ex:")
    print(s.connect_ex(("127.0.0.1", 3389)))

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    print("test using bind:")
    s.bind(("127.0.0.1", 3389))
test using connect_ex:
0
test using bind:
Traceback (most recent call last):
   File "test.py", line 9, in <module>
    s.bind(("127.0.0.1", 3389))
OSError: [Errno 98] Address already in use

Verified with lsof:

# lsof -i -P -n | grep LISTEN
ns-slapd  10 root    7u  IPv6  20456      0t0  TCP *:3389 (LISTEN)
ns-slapd  10 root    8u  IPv6  20457      0t0  TCP *:3636 (LISTEN)

Upvotes: 0

Views: 810

Answers (1)

Corralien
Corralien

Reputation: 120439

I think there is a misunderstanding. The return of the function is 0 when the connection is successful so that the port is accessible.

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    print("test using connect_ex:")
    print(s.connect_ex(("127.0.0.1", 3389)))

test using connect_ex:
0  # <- the port is busy because the connection success
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    print("test using connect_ex:")
    print(s.connect_ex(("127.0.0.1", 1234)))

test using connect_ex:
61  # <- [Errno 61] Connection refused (the port is free)

Upvotes: 3

Related Questions