2

Before using a scraper, I have a piece of code that checks whether a VPN is connected, and prompts to connect if it isn't. I was using the socket module to check for this, but this never returns the IP addresses associated with the VPN. I'm now experimenting with the netifaces module, but I'm not very familiar with networks and am not sure whether certain things will be the same across other people's systems as well.

This code gives me the VPN IP when it's connected, or just my normal IP when it isn't. I'm slicing for the second network interface in netifaces.interfaces(), because when I asked a few people to show me the ifaddresses for each interface I noticed the VPN IP was always the second in the list. Will that always be the like that? Or is it a coincidence? And if not, how do I know which network interface to select?

import netifaces
import socket

list_network_interfaces = netifaces.interfaces()
try:
    IPAddr = netifaces.ifaddresses(list_network_interfaces[1])[netifaces.AF_INET][0]["addr"]
except KeyError:
    IPAddr = socket.gethostbyname(socket.gethostname())

IPAddr

Here are my interfaces:

netifaces.interfaces()
Out[171]: 
['{17D62FA3-A6E4-4FAB-B55D-E2D5F4460772}',
 '{CD06AC03-44F7-46E8-8AC2-9DB429D3E1FB}',
 '{BA45335D-2559-4065-9FE6-F6F6000750C5}',
 '{8CF199C3-151E-4AC4-B85D-F62A00C4DF67}',
 '{29316C14-7ED0-4C6E-9C46-8A275FD90401}',
 '{1CAEA94C-8779-4791-98E1-DE85E436BF09}',
 '{22B0D2D6-865E-11EA-9F14-806E6F6E6963}']
MKJ
  • 120
  • 8

0 Answers0