Reputation: 704
I'm doing some simple experiments using Python socket, where I've a HOSTNAME which resolves with two IP addresses but when I use,
socket.gethostbyname('demo.sample.com')
I'm getting only one IP address. Why is it showing that way? Is there any other way I can get multiple IP addresses?
EDIT - 1
I got it guys, instead of gethostbyname('demo.sample.com')
I tried gethostbyname_ex('demo.sample.com')
It gives the result as I expected.
Upvotes: 6
Views: 11789
Reputation: 3855
I found a solution here, which returns the internal network IP:
import socket
def ip_addr(hostIP=None):
if hostIP is None or hostIP == 'auto':
hostIP = 'ip'
if hostIP == 'dns':
hostIP = socket.getfqdn()
elif hostIP == 'ip':
from socket import gaierror
try:
hostIP = socket.gethostbyname(socket.getfqdn())
except gaierror:
logger.warn('gethostbyname(socket.getfqdn()) failed... trying on hostname()')
hostIP = socket.gethostbyname(socket.gethostname())
if hostIP.startswith("127."):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# doesn't have to be reachable
s.connect(('10.255.255.255', 1))
hostIP = s.getsockname()[0]
return hostIP
if __name__ == '__main__':
print('%s' % ip_addr())
Upvotes: 2
Reputation: 123561
From the documentation it is visible that:
Upvotes: 11