🔍 Code Extractor

function check_port

Maturity: 31

Checks if a specific port on a given host is open and accepting TCP connections.

File:
/tf/active/vicechatdev/email-forwarder/check_service.py
Lines:
5 - 13
Complexity:
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.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function check_port_listening 75.6% similar

    Checks if TCP port 2525 on localhost (127.0.0.1) is actively listening and accepting connections.

    From: /tf/active/vicechatdev/email-forwarder/service_status.py
  • function test_smtp_connection 55.0% similar

    Tests the SMTP connection to a local email forwarder service running on port 2525 by establishing a connection and performing an EHLO handshake.

    From: /tf/active/vicechatdev/email-forwarder/test_e2e.py
  • function test_smtp_basic 54.1% similar

    Tests basic SMTP server connectivity by attempting to establish a connection to a local SMTP server on port 2525 and performing an EHLO handshake.

    From: /tf/active/vicechatdev/email-forwarder/service_status.py
  • function main_v57 51.1% similar

    Performs a comprehensive status check of an email forwarder service, verifying process status, port availability, SMTP communication, and configuration settings.

    From: /tf/active/vicechatdev/email-forwarder/service_status.py
  • function test_connection 46.9% similar

    Tests the database connection by executing a simple query and validating the result.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
← Back to Browse