B
B
BadCats2021-10-05 21:16:42
Python
BadCats, 2021-10-05 21:16:42

How does this definition of a private address work in Python?

Source: https://stackoverflow.com/a/28950776
Code

import socket
def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except Exception:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP

Moreover, here there is an appeal to the network 10.х.х.х.х - to its border, while in the code I get my gray ip with NAT-a - in the range 192.168.х.х. How it works?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alan Gibizov, 2021-10-05
@BadCats

As I understand it, it doesn't matter what the address is - all the magic is in getsockname, and the address there can be any sane outside the computer. Although 8.8.8.8 is just for the socket to knock outside the computer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question