python訪問你自己的公網ip地址的代碼

把寫內容過程中較好的一些內容片段記錄起來,下面資料是關於python訪問你自己的公網ip地址的內容,應該對小夥伴們有用途。

import urllib,random,re

ip_regex = re.compile("(([0-9]{1,3}.){3}[0-9]{1,3})")

def public_ip():
    ''' Returns your public IP address.
        Output: The IP address in string format. 
                None if not internet connection available.
    '''
    # List of host which return the public IP address:
    for i in range(3):
        host = random.choice(hosts)
        try:
            results = ip_regex.findall(urllib.urlopen(host).read(200000))
            if results: return results[0][0]
        except:
            pass # Let's try another host
    return None
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章