function check_port_listening
Maturity: 44
Checks if TCP port 2525 on localhost (127.0.0.1) is actively listening and accepting connections.
File:
/tf/active/vicechatdev/email-forwarder/service_status.py
Lines:
23 - 32
23 - 32
Complexity:
simple
simple
Purpose
This function is used to verify if a service (typically an SMTP server or mail relay) is running and listening on port 2525. It performs a non-blocking connection attempt with a 2-second timeout to determine port availability. This is commonly used in health checks, service monitoring, or pre-flight validation before attempting to send emails through a local mail server.
Source Code
def check_port_listening():
"""Check if port 2525 is listening."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
result = sock.connect_ex(('127.0.0.1', 2525))
sock.close()
return result == 0
except:
return False
Return Value
Returns a boolean value: True if port 2525 is listening and accepting connections (connection successful), False if the port is not listening, connection failed, or any exception occurred during the check.
Dependencies
socket
Required Imports
import socket
Usage Example
import socket
def check_port_listening():
"""Check if port 2525 is listening."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
result = sock.connect_ex(('127.0.0.1', 2525))
sock.close()
return result == 0
except:
return False
# Example usage
if check_port_listening():
print("Port 2525 is listening and ready")
else:
print("Port 2525 is not available")
# Use in a retry loop
import time
for attempt in range(5):
if check_port_listening():
print("Service is ready!")
break
print(f"Attempt {attempt + 1}: Service not ready, waiting...")
time.sleep(1)
Best Practices
- The function uses a bare except clause which catches all exceptions - consider catching specific exceptions (socket.error, socket.timeout) for better error handling
- The 2-second timeout is hardcoded - consider making it a parameter for flexibility
- The port number (2525) and host (127.0.0.1) are hardcoded - consider parameterizing these values for reusability
- Always ensure the socket is closed even if an exception occurs (the current implementation handles this correctly)
- This function only checks if the port accepts connections, not if the service is fully functional
- Port 2525 is commonly used for SMTP relay services - ensure this aligns with your application's requirements
- The function returns False for any error, which may mask different failure modes - consider logging errors for debugging
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function check_port 75.6% similar
-
function test_smtp_connection 74.0% similar
-
function test_smtp_basic 72.7% similar
-
function main_v55 62.3% similar
-
function send_test_email_v1 60.6% similar