function check_port
Checks if a specific port on a given host is open and accepting TCP connections.
/tf/active/vicechatdev/email-forwarder/check_service.py
5 - 13
simple
Purpose
This function attempts to establish a TCP socket connection to a specified host and port to determine if the port is open and accessible. It's commonly used for network diagnostics, service availability checks, port scanning, or verifying that a server is listening on an expected port before attempting to connect. The function uses a 5-second timeout to prevent hanging on unresponsive hosts.
Source Code
def check_port(host, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex((host, port))
sock.close()
return result == 0
except:
return False
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
host |
- | - | positional_or_keyword |
port |
- | - | positional_or_keyword |
Parameter Details
host: The hostname or IP address (as a string) of the target machine to check. Can be a domain name (e.g., 'example.com'), IPv4 address (e.g., '192.168.1.1'), or 'localhost' for local machine.
port: The port number (as an integer) to check on the target host. Valid range is 1-65535, with common ports being 80 (HTTP), 443 (HTTPS), 22 (SSH), etc.
Return Value
Returns a boolean value: True if the port is open and accepting connections (connection successful), False if the port is closed, filtered, or if any error occurs during the connection attempt (including network errors, timeouts, or invalid host/port values).
Dependencies
socket
Required Imports
import socket
Usage Example
import socket
def check_port(host, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex((host, port))
sock.close()
return result == 0
except:
return False
# Check if a web server is running on localhost port 80
if check_port('localhost', 80):
print('Port 80 is open')
else:
print('Port 80 is closed')
# Check if SSH is available on a remote server
if check_port('192.168.1.100', 22):
print('SSH server is accessible')
else:
print('SSH server is not accessible')
# Check multiple ports
ports_to_check = [80, 443, 8080]
for port in ports_to_check:
status = 'open' if check_port('example.com', port) else 'closed'
print(f'Port {port}: {status}')
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 and debugging.
- The 5-second timeout is hardcoded. Consider making it a parameter for more flexibility.
- This function only checks TCP ports. For UDP port checking, a different approach using SOCK_DGRAM would be needed.
- Be aware that some firewalls may silently drop packets, causing the function to timeout rather than return immediately.
- Excessive port scanning may be flagged by intrusion detection systems or violate terms of service. Use responsibly and only on systems you have permission to test.
- The function returns False for all errors, making it impossible to distinguish between a closed port and a network error. Consider returning more detailed status information if needed.
- Always close the socket (which this function does correctly) to avoid resource leaks.
- For checking multiple ports, consider implementing connection pooling or concurrent checks to improve performance.
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function check_port_listening 75.6% similar
-
function test_smtp_connection 55.0% similar
-
function test_smtp_basic 54.1% similar
-
function main_v57 51.1% similar
-
function test_connection 46.9% similar