将 IP 字符串转换为数字,反之亦然 [英] Convert an IP string to a number and vice versa

查看:39
本文介绍了将 IP 字符串转换为数字,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何使用 python 将作为 str 的 IP 地址转换为十进制数,反之亦然?

例如对于IP186.99.109.000 ,我想要一个十进制或二进制的形式,便于存入数据库,然后检索

解决方案

将 IP 字符串转换为长整数:

导入socket、structdef ip2long(ip):"""将 IP 字符串转换为 long"""PackedIP = socket.inet_aton(ip)返回 struct.unpack("!L",packedIP)[0]

反过来:

<预><代码>>>>socket.inet_ntoa(struct.pack('!L', 2130706433))'127.0.0.1'

How would I use python to convert an IP address that comes as a str to a decimal number and vice versa?

For example, for the IP 186.99.109.000 <type'str'>, I would like to have a decimal or binary form that is easy to store in a database, and then retrieve it.

解决方案

converting an IP string to long integer:

import socket, struct

def ip2long(ip):
    """
    Convert an IP string to long
    """
    packedIP = socket.inet_aton(ip)
    return struct.unpack("!L", packedIP)[0]

the other way around:

>>> socket.inet_ntoa(struct.pack('!L', 2130706433))
'127.0.0.1'

这篇关于将 IP 字符串转换为数字,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆