鱼C论坛

 找回密码
 立即注册
查看: 1296|回复: 0

[技术交流] python将IP地址转换为16进制

[复制链接]
发表于 2018-4-10 09:32:15 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 xlxl 于 2018-4-10 19:50 编辑

作为家庭作业:

工作中时常会用到wireshark/tcpdump来抓包分析,尤其是tcpdump的时候,只能使用命令行的形式指定IP地址的16进制数来过滤,所以这里打算写一个小代码,实现IP地址到16进制的转换;

ip地址范围为0~255,不能为全0,所以回判断地址的最小长度和数字的范围;

#this code wants to exchange the IP(1.1.1.1) to Hex type(0xABCD)
#Usage:tcpdump needs the ip to filter the network packets;

ip = list()
judge = True
temp = input("Please input the IP address:")
iplen = len(temp)
if iplen <7 or iplen >13:
    print('illeage IP address, please input again:')
else:
    ip1 = temp.split(".")
    print(ip1)
    for i in range(0,4):
        if ip1.isdigit() and int(ip1) <= 255:
            iphex = hex(int(ip1))
            ip.append(iphex)
        else:
            print('You input IP address incorrect')
    print(ip)

感觉就是一个hex的事情,这个代码写的有点无病呻吟的感觉。。。

不完善的地方:
1. 长度以及数据判断后,如果地址非法,没有加入重新输入的入口?
2.  判断数字大小的时候,是4个数据依次判断的,理论上只要有1个数字超过255,整个地址就是非法的,就不应该有任何输出;
实际结果判断有问题:
Please input the IP address:10.a.11.25
['10', 'a', '11', '25']
input IP address incorrect
['0xb', '0x19']
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-20 08:01

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表