美文网首页Python
python获取公网ip

python获取公网ip

作者: 哩白 | 来源:发表于2020-10-06 13:04 被阅读0次

    思路:请求一个特定网站,网站返回内容包含公网ip。

    使用python的requests库请求http://txt.go.sohu.com/ip/soip,响应中包含公网ip,re匹配出公网ip,输出就可以了。当然你也可以让程序一直执行,例如每隔60s或更久,或者把获得的公网ip保存在本地。或者当公网ip发生变化时,提醒自己。

    import requests

    import time

    import re

    def getip():

            ip_html = requests.get("http://txt.go.sohu.com/ip/soip")

    #返回公网ip的网站

            cur_public_ip = re.findall(r'\d+.\d+.\d+.\d+',ip_html.text)

    #从响应中匹配公网ip

            #return cur_public_ip

            cip = cur_public_ip[0]

            print(cip)

    #输出公网ip,可不要

            save_txt(cip)

    #定义保存ip函数

    #定义休眠函数,每隔60秒请求一次

    def sleep_func():

            time.sleep(60)

            #休眠60秒

    #保存到本地,当前目录

    def save_txt(ip):

            with open('ip.txt','a') as f:

                    t = time.asctime(time.localtime(time.time()))

                    f.write(t)

                    f.write('\t')

                    f.write(ip)

                    f.write('\n')

    if __name__ == '__main__':

            while True:

                    getip()

                    sleep_func()

    相关文章

      网友评论

        本文标题:python获取公网ip

        本文链接:https://www.haomeiwen.com/subject/zbltpktx.html