Wish I Knew this stuff Wish I Knew this stuff - 3 years ago 201
Python Question

How to Grab IP address from ping in Python

I am currently using python 2.7 and will need to ping windows and linux.

I want to create a function that will return the IP address from a ping within a python script. I currently have this function

def ping(host):
"""
Returns True if host responds to a ping request
"""
import subprocess, platform

# Ping parameters as function of OS
ping_str = "-n 1" if platform.system().lower()=="windows" else "-c 1"
args = "ping " + " " + ping_str + " " + host
need_sh = False if platform.system().lower()=="windows" else True

# Ping
return subprocess.call(args, shell=need_sh) == 0


Right now it just returns true or false but is there a way I can run ping(google.com) and have it return 216.58.217.206. I have a list of servers and IPs and I need to make sure that the IP addresses match the FQDN.

Answer Source

You can use the socket to get the IP of the host.

import socket
print(socket.gethostbyname('www.example.com')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download