Get IP address from python
13,227
Translate host to ip :
import socket
print (socket.gethostbyname(socket.gethostname()))
To get host by name :
import socket
print (socket.gethostbyname("www.goole.com"))
Author by
lichb0rn
Updated on June 22, 2022Comments
-
lichb0rn almost 2 years
I'm trying to get the ip address associated with network interface without spawning additional processes in Linux:
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].encode('utf-8')) )[20:24])
But always getting this error:
struct.pack('256s', ifname[:15].encode('utf-8')) OSError: [Errno 99] Cannot assign requested address
How can I solve this?
-
lichb0rn about 6 yearsAnd what if I have multiple network interfaces without any internet connection?
-
Ricky Levi about 5 yearsthe first comment returns
127.0.0.1
.... -
Mohith7548 about 5 yearsIt always returns the output as '127.0.0.1'. But I need both public and private IP addresses.
-
An0n about 5 yearsDo you have a working internet connection?