python3 域名转ip

一.说明

Python的Socket模块提供有域名转为对应IP地址的方法。 socket.gethostbyname 函数

本例中,将urllist.txt中的每行URL都试图解析成IP地址,保存到iplist.txt。

需要注的是,socket.gethostbyname(url)方法中的url参数不能带有“http”这样的协议前缀,否则不能解析成IP地址。

为了对比解析效果,加入了两条错误的域名格式,以便引起读者注意。

二.代码

import socket

def URL2IP():
   for oneurl in urllist.readlines():
       url=str(oneurl.strip())[7:]
       print(url)
       try:
           ip =socket.gethostbyname(url)
           print(ip)
           iplist.writelines(str(ip)+"\n")
       except:
           print("this URL 2 IP ERROR")

try:
    urllist=open("D:\\urllist.txt","r")
    iplist=open("D:\\iplist.txt","w")
    URL2IP()
    urllist.close()
    iplist.close()
    print("complete !")
except:
    print("ERROR !")

三.urllist

这里写图片描述

三.程序回显

sdk.mobcent.com
103.235.239.10
www.baidu.com
180.97.33.107
os-android.liqucn.com
116.90.87.156
vgo.21cn.com/portal/index.do
this URL 2 IP ERROR
you do 110…
this URL 2 IP ERROR
sj.good321.net
121.46.3.148
good.cn
23.27.192.117
complete !

四.最终结果

这里写图片描述

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值