【问题标题】:how can I convert a string to ip address in python如何在python中将字符串转换为ip地址
【发布时间】:2017-08-25 09:59:17
【问题描述】:

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

/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 django python-3.x websocket tornado


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多