I'm trying to find a way to have Python determine what my computers IP address is and could use a hand with a weird result. A couple of quick facts, I'm using Windows 10 with the Linux Subsystem (the Ubuntu terminal app) and am running python 3.7.6.
My initial attempt at this was to use socket. i.e.,
import socket
hostname = socket.gethostname() # outputs a string with the hostname
ip_address = socket.gethostbyname(hostname) # outputs a string with the relevant IP address
So, I thought this was working great until I tried running this on a different computer and noticed that the IP address from my computer and the different computer were the same. A quick view at the Windows command prompt showed me that my IPv4 address is completely different than what was being called by socket.
I'm not sure what the issue is here and if anyone knows, I'm all ears.
My main question is this:
How do I call in my computer's unique IPv4 address using Python?
To address the questions in the comments:
What I'm trying to do, ultimately, is access a file that is located in different directories on two different computers. I'm writing a script for a data analysis project I'm working on, and using gitlab to track my progress. But, the file paths are needing to be hardcoded into the script. To avoid dealing with changing the paths every time I switch computers, I want to add a few lines to do the following:
import socket
hostname = socket.gethostname() # outputs a string with the hostname
ip_address = socket.gethostbyname(hostname) # outputs a string with the relevant IP address
if ip_address == '127.0.1.1':
print('Working on desktop1:')
masked_data = 'file/path/of/desktop/1/mask.pkl'
elif ip_address == 'xxx.yyy.zzz.1':
print('Working on desktop2:')
masked_data = 'file/path/of/desktop/2/mask.pkl'
This is temporary until we get a server up and running, I know it's a weird workaround. ;P
The issue with this that ip_address
is the same for both computers when using socket. What I need to do is get the unique address of the computer I'm working on and replace the IP addresses in the loop.
Using socket.gethostname()
to get your own hostname, and then socket.gethostbyname()
to resolve that to an IP tells you what IP address your operating system is suggesting to use for loopback communication. However, that doesn't tell you anything about what addresses a system elsewhere on the network might use to communicate with you.
Consider as an example the ifaddr
Python library, which is built specifically for the purpose of enumerating local network devices and the addresses associated with each.
Similarly, one of the answers to How to get Network Interface Card names in Python? suggests git_nic
, which should similarly serve the purpose.
Also, the general-purpose psutil
Python library provides a net_if_addrs()
function for the purpose.
Yet another 3rd-party module for the purpose is netifaces
.