Skip to content
Advertisement

Obtaining IP from command ‘host’ executed inside python

I have this function to show me the 1st ip of a domain:

def get_ip_address(url):
    command="host "+url
    process=os.popen(command)
    results=str(process.read()) 
    marker=results.find('has address')+12   
    print results[marker:].splitlines()[0]
    return results[marker:].splitlines()[0]

But this only shows me the first ip. I’d like to show only the ip’s. The marker is for not having “has address” as shown below (imagine I input “reddit.com”:

['151.101.65.140', 'reddit.com has address 151.101.129.140', 'reddit.com has address 151.101.193.140', 'reddit.com has address 151.101.1.140', 'reddit.com mail is handled by 1 aspmx.l.google.com.', 'reddit.com mail is handled by 10 aspmx2.googlemail.com.', 'reddit.com mail is handled by 10 aspmx3.googlemail.com.', 'reddit.com mail is handled by 5 alt1.aspmx.l.google.com.', 'reddit.com mail is handled by 5 alt2.aspmx.l.google.com.']

I want to show only the ips, not reddit.com has addressnor once the ip’s end, mail is handledetc.

I tried with

def get_ip_address(url):
    command="host "+url
    process=os.popen(command)
    results=str(process.read()) 
    marker=results.find('has address')+12
    i=0
    arrayIps=[]
    while "has address" in results[marker:].splitlines()[i]:

        print results[marker:].splitlines()[i]
        arrayIps.append(results[marker:].splitlines()[i])
        print("array")
        print arrayIps[i]
        i=i+1
    return arrayIps

But it is not working! Not even returning anything useful!

What I am expecting is an array with (in this case):

'151.101.65.140', '151.101.129.140', '151.101.193.140', '151.101.1.140'

Advertisement

Answer

See it shows multiple hosts as you required .Your output can be generated using a map function

In [132]: socket.getaddrinfo("reddit.com", 80, proto=socket.IPPROTO_TCP)
Out[132]: 
[(<AddressFamily.AF_INET: 2>,
  <SocketKind.SOCK_STREAM: 1>,
  6,
  '',
  ('151.101.65.140', 80)),
 (<AddressFamily.AF_INET: 2>,
  <SocketKind.SOCK_STREAM: 1>,
  6,
  '',
  ('151.101.1.140', 80)),
 (<AddressFamily.AF_INET: 2>,
  <SocketKind.SOCK_STREAM: 1>,
  6,
  '',
  ('151.101.129.140', 80)),
 (<AddressFamily.AF_INET: 2>,
  <SocketKind.SOCK_STREAM: 1>,
  6,
  '',
  ('151.101.193.140', 80))]


In [134]: list(map(lambda x:x[4][0],socket.getaddrinfo("reddit.com", 80, proto=socket.IPPROTO_TCP)))
Out[134]: ['151.101.129.140', '151.101.193.140', '151.101.65.140', '151.101.1.140']
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement