PythonはサーバーのイントラネットIPを自動的に取得します

サーバー上でTCPサーバーである必要がある場合があります。しかし、サーバーのイントラネットは再び変更されました。実際、内部ネットワークIPはプログラムによって自動的に取得でき、TCPサーバーによって監視されるIPは内部ネットワークIPです。

インターネットで2つのコードを見つけましたが、どちらも利用できます。

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())

 

おすすめ

転載: blog.csdn.net/qq_27158179/article/details/106403956