Skip to main content

Check if a port is free - simple and minimalistic

Project description

is-port-free

🔍 Check if a port is free - simple and minimalistic.

Python 3.6+ PyPI version License: MIT

Why?

Sometimes you just need to check if a port is available. That's it. No complex features, no dependencies, just a simple function that returns True or False.

Installation

pip install is-port-free

Usage

Basic Usage

from is_port_free import is_port_free

# Check if port 8000 is free on localhost
if is_port_free(8000):
    print("Port 8000 is available!")
else:
    print("Port 8000 is in use")

# Check specific host
if is_port_free(8000, 'localhost'):
    print("Port 8000 is free on localhost")

if is_port_free(80, '127.0.0.1'):
    print("Port 80 is free on 127.0.0.1")

Alternative Functions

from is_port_free import is_port_used, check_port, port_available

# Check if port is in use (opposite of is_port_free)
if is_port_used(8000):
    print("Port 8000 is busy")

# Function aliases (all do the same thing as is_port_free)
check_port(8000)        # Returns True/False
port_available(8000)    # Returns True/False

Command Line

# Check if port is free
is-port-free 8000

# Check specific host  
is-port-free 8000 --host localhost

# Quiet mode (only exit codes)
is-port-free 8000 --quiet
echo $?  # 0 = free, 1 = in use, 2 = error

API Reference

is_port_free(port, host='localhost')

Check if a port is free (available for binding).

Parameters:

  • port (int): Port number to check
  • host (str, optional): Host to check on. Defaults to 'localhost'

Returns:

  • bool: True if port is free, False if port is in use

Example:

is_port_free(8000)              # True
is_port_free(8000, 'localhost') # True  
is_port_free(80, '127.0.0.1')   # False (usually)

is_port_used(port, host='localhost')

Check if a port is in use (opposite of is_port_free).

Returns:

  • bool: True if port is in use, False if port is free

Common Use Cases

Starting a Development Server

from is_port_free import is_port_free

def start_server(preferred_port=8000):
    port = preferred_port
    
    # Find next available port
    while not is_port_free(port):
        port += 1
        if port > 65535:
            raise Exception("No available ports")
    
    print(f"Starting server on port {port}")
    # start your server here
    return port

Testing

import pytest
from is_port_free import is_port_free

def test_my_server():
    # Make sure test port is available
    test_port = 8080
    assert is_port_free(test_port), f"Test port {test_port} is not available"
    
    # Start your test server
    server = start_test_server(test_port)
    
    # Port should now be in use
    assert not is_port_free(test_port)
    
    # Clean up
    server.stop()

Docker Health Checks

from is_port_free import is_port_used

def health_check():
    """Check if application is running"""
    if is_port_used(8000, 'localhost'):
        return "healthy"
    else:
        return "unhealthy"

Port Allocation

from is_port_free import is_port_free

def allocate_ports(count=3, start_port=8000):
    """Allocate multiple free ports"""
    ports = []
    port = start_port
    
    while len(ports) < count:
        if is_port_free(port):
            ports.append(port)
        port += 1
        
        if port > 65535:
            break
    
    return ports

# Get 3 free ports starting from 8000
free_ports = allocate_ports(3, 8000)
print(f"Available ports: {free_ports}")

How It Works

The package uses Python's built-in socket library to attempt to bind to the specified port. If the bind succeeds, the port is free. If it fails, the port is in use.

import socket

def is_port_free(port, host='localhost'):
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            sock.bind((host, port))
            return True
    except (socket.error, OSError):
        return False

Notes

  • No dependencies - Uses only Python standard library
  • Cross-platform - Works on Windows, macOS, and Linux
  • Fast - Minimal overhead, just a socket bind attempt
  • Safe - Uses context managers to ensure proper socket cleanup
  • IPv4 only - Currently only supports IPv4 addresses

Edge Cases

  • Port 0: Returns True (OS will assign an available port)
  • Invalid ports (< 0 or > 65535): Returns False
  • Privileged ports (< 1024): May require admin rights on some systems
  • Firewall: Function checks if port can be bound, not if it's accessible externally

Contributing

This package is intentionally minimal. If you need more features, consider:

For bug fixes or small improvements, pull requests are welcome!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

is_port_free-1.0.0.tar.gz (5.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

is_port_free-1.0.0-py3-none-any.whl (5.1 kB view details)

Uploaded Python 3

File details

Details for the file is_port_free-1.0.0.tar.gz.

File metadata

  • Download URL: is_port_free-1.0.0.tar.gz
  • Upload date:
  • Size: 5.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.0

File hashes

Hashes for is_port_free-1.0.0.tar.gz
Algorithm Hash digest
SHA256 80bd51037d8b6820ee497bdf06f95d30d4e7762385bfaa1ba359dd9e4a80c0cb
MD5 09d76fe9c3a917ebe2bac7446e412803
BLAKE2b-256 ff156d5a95ee0adb83ca646a8d9342d7705ff92f8271594b47e86868cb31f887

See more details on using hashes here.

File details

Details for the file is_port_free-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: is_port_free-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 5.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.0

File hashes

Hashes for is_port_free-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5b0824abfac97877ab9e5da07f1e99f2bc4f0a891cdb7e9e7a2469331d525006
MD5 93ab8ad61066d7bff957d2f755ee848a
BLAKE2b-256 f4255b70c2e58e6e48eef4973df495dd253040de08abcb597a12e4bd47f81b13

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page