2017-09-29 2 views
0

현재 Python 2.7을 사용하고 있으며 Windows 및 Linux에 대해 ping을 수행해야합니다.Python에서 ping에서 IP 주소를 가져 오는 방법

파이썬 스크립트 내의 ping에서 IP 주소를 반환하는 함수를 만들고 싶습니다. 저는 현재 그냥 참 또는 거짓 반환하지만 거기에 내가 핑 (google.com)를 실행하고 216.58.217.206를 반환 할 수있는 방법입니다 지금이 기능을

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 

있습니다. 서버 및 IP 목록이 있으므로 IP 주소가 FQDN과 일치하는지 확인해야합니다.

+0

위 코드는 들여 쓰기가 적절하지 않습니다. 'def' 줄 아래의 모든 항목은 들여 쓰기되어야합니다. –

+0

[read process stdout line by line] 가능한 복제본 (https://stackoverflow.com/questions/2804543/read-subprocess-stdout-line-by-line) – alfasin

답변

1

socket을 사용하여 호스트의 IP를 가져올 수 있습니다.

import socket 
print(socket.gethostbyname('www.example.com') 
관련 문제