获取本机局域网ip和出口ip

import socket
import requests


class GetLocalHost:

    def get(self):
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.connect(('8.8.8.8', 80))

            ip = s.getsockname()[0]
        return ip


class GetExportIp:

    def get(self):
        ip = requests.get('https://checkip.amazonaws.com').text.strip()
        return ip


IP_TYPE_DICT = {
    "local": GetLocalHost,
    "export": GetExportIp
}


def get_ip(type):
    func = IP_TYPE_DICT.get(type, None)
    if not func:
        raise Exception(f'type:{type}, 参数错误')
    return func().get()


if __name__ == '__main__':
    ip = get_ip('local')
    print(ip)
posted @ 2021-06-18 13:04  深圳-逸遥  阅读(296)  评论(0编辑  收藏  举报