1
0

get_ipaddr.py 702 B

1234567891011121314151617181920212223
  1. #!/usr/bin/env python
  2. import socket
  3. def Get_local_ip():
  4. """
  5. Returns the actual ip of the local machine.
  6. This code figures out what source address would be used if some traffic
  7. were to be sent out to some well known address on the Internet. In this
  8. case, a Google DNS server is used, but the specific address does not
  9. matter much. No traffic is actually sent.
  10. """
  11. try:
  12. socket.setdefaulttimeout(5)
  13. csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  14. csock.connect(('1.1.1.1', 80))
  15. (addr, port) = csock.getsockname()
  16. csock.close()
  17. return addr
  18. except socket.error:
  19. return "127.0.0.1"
  20. if __name__ == "__main__":
  21. IPADDR = Get_local_ip()
  22. print(IPADDR)