在python中将IP地址转换为字节 [英] Converting IP address into bytes in python
本文介绍了在python中将IP地址转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我在python中有一个IP地址
Say i have an IP address in python
addr = '164.107.113.18'
如何将IP地址转换为4个字节?
How do i convert the IP address into 4 bytes?
推荐答案
使用 Maciej Gol的回答,但这是另一种方式:
Go with Maciej Gol's answer, but here's another way:
ip = '192.168.1.1'
ip_as_bytes = bytes(map(int, ip.split('.')))
编辑:糟糕,这只是Python 3.X。对于Python 2.X
EDIT: Oops, this is Python 3.X only. For Python 2.X
ip = '192.168.1.1'
ip_as_bytes = ''.join(map(chr,map(int,ip.split('.'))))
你最好过的时候但是,鉴于其效率,使用套接字模块:
You're better off using the socket module, however, given its efficiency:
>>> timeit.timeit("socket.inet_aton('164.107.113.18')",setup='import socket')
0.22455310821533203
>>> timeit.timeit("''.join(map(chr,map(int,'164.107.113.18'.split('.'))))")
3.8679449558258057
这篇关于在python中将IP地址转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文