Python obtiene automáticamente la IP de la intranet del servidor

A veces es necesario ser un servidor TCP en el servidor. Pero la intranet del servidor ha vuelto a cambiar. De hecho, el programa puede obtener automáticamente la IP de la red interna, y la IP monitoreada por el servidor TCP es la IP de la red interna.

Encontré dos códigos en Internet, ambos disponibles.

1. get_inner_ipaddr.py


#!/usr/bin/env python
import socket
def Get_local_ip():
    """
    Returns the actual ip of the local machine.
    This code figures out what source address would be used if some traffic
    were to be sent out to some well known address on the Internet. In this
    case, a Google DNS server is used, but the specific address does not
    matter much.    No traffic is actually sent.
    """
    try:
        csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        csock.connect(('8.8.8.8', 80))
        (addr, port) = csock.getsockname()
        csock.close()
        return(addr)
    except socket.error:
        return "127.0.0.1"
 
if __name__ == "__main__":
    IPADDR = Get_local_ip()
    print(IPADDR)

2. get_inner_ipaddr2.py


import socket
def get_local_ip():
    local_ip = ""
    try:
        socket_objs = [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]
        ip_from_ip_port = [(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in socket_objs][0][1]
        ip_from_host_name = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1]
        local_ip = [l for l in (ip_from_ip_port, ip_from_host_name) if l][0]
    except (Exception) as e:
        print("get_local_ip found exception : %s" % e)
    return local_ip if("" != local_ip and None != local_ip) else socket.gethostbyname(socket.gethostname())
 
print(get_local_ip())

 

Supongo que te gusta

Origin blog.csdn.net/qq_27158179/article/details/106403956
Recomendado
Clasificación