-
-
Notifications
You must be signed in to change notification settings - Fork 442
Description
WSL version
WSL 版本: 2.3.26.0
内核版本: 5.15.167.4-1
WSLg 版本: 1.0.65
MSRDC 版本: 1.2.5620
Direct3D 版本: 1.611.1-81528511
DXCore 版本: 10.0.26100.1-240331-1435.ge-release
Windows 版本: 10.0.26100.4652
python version
Python 3.8.20
viztrace version
viztracer 0.16.3
result.json size
ll result.json
-rw-r--r-- 1 xxx xxx 7.7M Aug 1 15:04 result.json
description
This took more than 2mins, andI found it took times at viewer.ServerThread.is_port_in_use
date; vizviewer result.json --port=9999
Fri Aug 1 15:54:42 CST 2025
User customize module loaded.
Running vizviewer
You can also view your trace on http://localhost:9999
Press Ctrl+C to quit, current_time=2025-08-01 15:56:56
updated after ask ChatGPT
Your is_port_in_use implementation will work in many cases, but it has several potential drawbacks:
- Blocking Calls
By default, sock.connect_ex() is a blocking call. If the target port is filtered (e.g. by a firewall) or the host doesn’t respond, your call can hang indefinitely. In high-latency or unreliable networks this may stall your thread.
Fix: set a short timeout before connecting:
sock.settimeout(0.5)
-
IPv4-only Check
You’re only probing 127.0.0.1 over IPv4. If the service is bound to an IPv6 loopback (::1) or on a non-localhost interface, you’ll get a false negative.
Fix: either also try an AF_INET6 socket with ('::1', port, 0, 0) or scan other interfaces. -
Race Condition (“Check-Then-Use”)
Even if your check reports “in use” or “free,” the state can change immediately afterward: some other process may bind the port between your check and when you actually try to bind or connect. This check-then-use pattern is inherently racy.
Fix: instead of probing first, attempt to bind your own socket and catch OSError(errno.EADDRINUSE)—the bind itself is atomic. -
Redundant contextlib.closing
In Python 3.2+ sockets support the context‐manager protocol, so you can write:
see socket docs example
with socket.socket(...) as sock:
...
without needing contextlib.closing().
- TCP-only Detection
You only test a TCP connect. If you need to know whether a UDP port is “in use,” you’d have to create a socket.SOCK_DGRAM and perform a different kind of probe (e.g. try sending a zero-byte packet or bind to it).