python自动获取服务器的内网IP

有时候有需要在服务器上做个TCP服务器。但是换了服务器内网又改变了。其实可以自动用程序获得内网IP,TCP服务器监听的IP就是内网IP。

在网上找到了两份代码,都是可用的。

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
今日推荐