If Python is a must, you can check this article:
http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/
They rightly point out that a computer has as many IP addresses as network interfaces.
Here is their code to get the IP address of a network adapter, I've tested the code and it works:
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
print get_ip_address('lo')
print get_ip_address('eth0')
If your RPi is connected via WiFi the adapter name should be wlan0
Otherwise you can get it with the ip
command:
ip addr show eth0 | grep inet
You should get something like:
inet 192.168.0.140/24 brd ....
That's your IP address.
Of course none of this will work if you just boot up your RPi and could not connect to it because you don't know the IP address! If' that's the case your DHCP server will surely be able to tell you which IP address he just gave to the RPi (or you just try them all :) )
That said, you might benefit of referencing you RPi by name and, since you're using a Mac, probably the best solution would be to install avahi-daemon:
sudo apt-get install avahi-daemon
which implements the Apple Zeroconf specification (like Bonjour). You can then ssh to your RPi by name:
ssh pi@raspberry.local
I used a different approach for my two Raspberrys (named ygdrasill and dvalinn): I've opted for a fixed IP (192.168.0.140 and 192.168.0.142) so I can also use etc/hosts file on some of my other machines.
I could have set up an internal DNS or rely on Wins, but current solution works for me.
ssh
, to it? Surely you need the IP address before youssh
. – ctrl-alt-delor May 05 '19 at 17:44