1. 程式人生 > >python 獲取本機IP地址,檢測埠是否被佔用

python 獲取本機IP地址,檢測埠是否被佔用

import socket


def get_host_ip():
    """
    get host ip address
    獲取本機IP地址

    :return:
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()

    return ip


def is_port_used(ip,
port): """ check whether the port is used by other program 檢測埠是否被佔用 :param ip: :param port: :return: """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((ip, port)) return True except OSError: return False finally
: s.close() # 測試 if __name__ == '__main__': host_ip = get_host_ip() print(host_ip) print(is_port_used(host_ip, 80))

輸出結果:

10.0.12.25
False