5 examples of 'python get public ip address' in Python

Every line of 'python get public ip address' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
23def get_ip():
24 try:
25 hostname = socket.getfqdn(socket.gethostname())
26 ipaddr = socket.gethostbyname(hostname)
27 except Exception as msg:
28 print(msg)
29 ipaddr = ''
30 return ipaddr
58def is_public_ip(ip_str):
59 """
60 Returns true of ip_str is public & routable, else return false
61 """
62 return not is_private_ip(ip_str)
72def get_ip():
73 """Returns one of the IP addresses of the associated hosts"""
74 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
75 sock.connect(('1.1.1.1', 9000)) # IP and port are arbitrary
76 ip = sock.getsockname()[0] # returns (hostaddr, port)
77 sock.shutdown(socket.SHUT_RDWR)
78 sock.close()
79 return ip
43def get_ip(request):
44 ip_info = {
45 'REMOTE_ADDR': request.META.get('REMOTE_ADDR'),
46 'HTTP_VIA': request.META.get('HTTP_VIA'),
47 'HTTP_X_FORWARDED_FOR': request.META.get('HTTP_X_FORWARDED_FOR')
48 }
49 return JsonResponse(ip_info)
15def local_ip():
16 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
17 s.connect(("8.8.8.8", 80))
18 try:
19 return s.getsockname()[0]
20 finally:
21 s.close()

Related snippets