有時候有需要在服務器上做個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())