通過DNS獲取內網內的本地IP
#!/usr/bin/env python
# encoding: utf-8
import socket
def get_host_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('192.168.31.1', 53))
ip = s.getsockname()[0]
print(s.getsockname())
finally:
s.close()
return ip
if __name__ == '__main__':
print(get_host_ip())
結果
('192.168.31.74', 60081)
192.168.31.74
Process finished with exit code 0