import six
import socket
import contextlib


def is_port_open(port_or_url, timeout=1):
    """Check if TCP port is open."""
    if isinstance(port_or_url, six.string_types):
        url = six.moves.urllib.parse.urlparse(port_or_url)
        port = url.port
        host = url.hostname
    else:
        port = port_or_url
        host = "127.0.0.1"
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    with contextlib.closing(sock):
        sock.settimeout(timeout)
        result = sock.connect_ex((host, port))
        return result == 0