import socket
import subprocess


def check_port(host, port):
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(2)  # 设置超时时间为2秒
            result = s.connect_ex((host, port))
            # 返回True如果连接成功（result为0）
            return result == 0
    except socket.gaierror:
        print(f"错误：无法解析主机名 '{host}'")
        return False
    except socket.error as e:
        print(f"连接过程中发生错误: {e}")
        return False


def check_socket(socket: str):
    host, port = socket.split('//')[-1].split(':')
    return check_port(host, int(port))
# def c2():
#     code = subprocess.run(['curl', '-m', '1', f'http://{LIVE_REP_SOCKET}'], stderr=subprocess.DEVNULL,
#                               stdout=subprocess.DEVNULL).returncode
#     logger.debug(f'detect curl code: {code}')
#     match code:
#         case 28 | 7:
#             self.send(DeviceOnlineMsg(False))
#             return False
#         case _:
#             self.send(DeviceOnlineMsg(True))
#             return True
