简体   繁体   中英

Get IPv4 Address from python, even with vpn on

So I'm using socket to connect clients to the server. For that, I need the computer's ip. Currently, the best way I found is this:

socket.gethostbyname(socket.gethostname())

I then use requests to tell my clients about my ip, and they connect. The issue here is that when my vpn is on, I get another host and that causes the clients to be unable to connect. But when I open command prompt and type ipconfig, I get the correct ip regardless of the vpn status. So I need to get the same ip as would be shown under IPv4 in command prompt, is this possible in python?

I'm trying to get the server to work on any device regardless of exceptions such as this.

Thanks!

The way you retrieve the IP addresses of your system (most systems these days have multiple) uses the hostname of your system and therefore depends on ie DNS and your local hosts file. It will only give you one address, and can be quite unreliable, as you have seen with your VPN.

I'd recommend using the netifaces package. With it you can retrieve a list of all network interfaces and all their addresses.

An example from the manual:

>>> addrs = netifaces.ifaddresses('en0')
>>> addrs[netifaces.AF_INET]
[{'broadcast': '10.15.255.255', 'netmask': '255.240.0.0', 'addr': '10.0.1.4'}, {'broadcast': '192.168.0.255', 'addr': '192.168.0.47'}]

You should be able to install it with pip. The source repository is here: https://bitbucket.org/al45tair/netifaces

Yeah so I ran into this issue and it seems that ipconfig command does work, so I used the following. It calls ipconfig using subprocess and uses a regex pattern to match the ipv4 line. Since there's two ipv4 lines, and on my machine the VPN appeared as Unknown adapter WindscribeWireguard: before Wireless LAN adapter Wi-Fi: so I ended up matching the last one that appears. It's possible this isn't robust but I'm sure one of my users will let me know then.

import subprocess
import re

ipv4_pattern = re.compile(r'IPv4 Address.*:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')

def get_ipv4():
    ipconfig_output = subprocess.getoutput('ipconfig')
    return ipv4_pattern.findall(ipconfig_output)[-1]

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