如何在python中将字符串转换为ip地址 [英] how can I convert a string to ip address in python

查看:1266
本文介绍了如何在python中将字符串转换为ip地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将字符串ip地址转换为十进制数。例如我有一个数据 bytes = b'363,3,1778952384,7076',这里 1778952384 是我的IP地址, 7076 是我的端口。如何将我的IP地址转换为十进制数。以下是我的代码,请帮我解决这些问题。

how can i convert a string ip address to a decimal number. e.g I have a data bytes= b'363,3,1778952384,7076' , here 1778952384 is my ip address and 7076 is my port. How can I convert my IP address to decimal number. below is my code, please help me to solve these problem

/app.py

import socket
from tornado.tcpclient import TCPClient
from tornado import gen

@gen.coroutine
def f(self, message):

    global stream
    client = TCPClient()
    stream = yield client.connect('192.168.8.108', 2620, max_buffer_size=int(1e9))
    msg = '192.168.8.101, 8000'.encode('utf-8')
    yield stream.write(msg)
    data = yield stream.read_bytes(21)
    print("bytes=",data) #bytes= b'363,3,1778952384,7076


推荐答案

Python有一个 ipaddress 模块,可以处理这种事情。它被添加到Python 3中的标准库中,但也可以安装在较早版本中。

Python has an ipaddress module which can handle this sort of thing. It was added to the standard library in Python 3, but should be installable for earlier versions, too.

>>> import ipaddress
>>> print(ipaddress.ip_address(1778952384))
IPv4Address('106.8.168.192')
>>> print(str(ipaddress.ip_address(1778952384)))
'106.8.168.192'

您可能还会问分裂字符串(在 b',',因为它是一个测试),获取正确的字段,并将其转换为 int

You may also be asking about splitting the string (on b',' since it's a bytestring), getting the right field, and converting it to an int:

data = b'363,3,1778952384,7076'
ipaddress.ip_address(int(data.split(b',')[2]))

这篇关于如何在python中将字符串转换为ip地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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