Python中PJSIP重启PC后报Address already in use问题求助
The root of your problem is that setting transport = None only removes the Python reference to the transport object—it doesn’t tell the underlying PJSIP library to release the network resources tied to port 5060. When your program exits uncleanly (like when you restart the computer mid-execution), the port gets stuck in an occupied state, leading to the "Address already in use" error on your next run.
Here’s how to fix it properly:
Explicitly destroy the transport object
Before discarding the transport reference, call itsdestroy()method to tell PJSIP to release the UDP port and associated resources:# When ending the call or shutting down if transport is not None: transport.destroy() transport = NoneProperly shut down the PJSIP library instance
Don’t forget to clean up the mainlibobject too, as it might hold onto other resources that could cause issues:lib.destroy() lib = NoneWrap cleanup in a try/finally block
To ensure cleanup runs even if an error occurs during execution (which is common in telephony code), structure your main logic like this:def main(): lib = None transport = None try: # Initialize PJSIP library lib = pj.Lib() lib.init() # Configure and create transport trans_cfg = pj.TransportConfig() trans_cfg.port = 5060 trans_cfg.bound_addr = inputs.client_addr transport = lib.create_transport(pj.TransportType.UDP, trans_cfg) # ... Your call handling logic here ... finally: # Clean up resources no matter what if transport is not None: transport.destroy() if lib is not None: lib.destroy()
Your current workaround with lsof and kill works because it forces the stale process holding port 5060 to exit, but this is a manual band-aid. Implementing explicit cleanup in your code will prevent this issue from happening entirely, so you won’t need to run those commands after restarting your computer.
内容的提问来源于stack exchange,提问作者Raady

