简体   繁体   中英

How can I get the 'correct' IP-Address via Python

For some TCP playing around I need 2 IP-addresses, the public and private one. Public was easy enough with some request to an external service, but if i do

socket.gethostbyname(socket.gethostname())

i get 127.0.0.1/8, which is not correct. If i enter ip a I get 2 blocks of data, the first one being the 127..., labled as lo: <LOOPBACK,UP,LOWER_UP>, but I need the second one, the 192.168... which is ens3: <BROADCAST,MULTICAST,UP,LOWER_UP>.

I don't know very much about networking and the stuff surrounding it so I'm sorry if there is a straightforward, obvious solution, but is there a way that every machine I run my code on I get the IP address I need for my code to run?

Furthermore, what should I put into the host's s.bind()? The program runs over the internet so should i put the public or private ip address in there? some tutorials put an empty string in there which really confuses me now, and most use a local network so i have no idea what to do when doing it over the internet.

You can create a connection and grab the address associated with the active connection.

import socket


def get_internal_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 80))
    ip = s.getsockname()[0]
    s.close()
    return ip


def get_external_ip():
    return socket.gethostbyname(socket.gethostname())


print('Internal:', get_internal_ip())
print('External:', get_external_ip())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM