简体   繁体   English

如何在python中将字符串转换为IP地址

[英]how can I convert a string to ip address in python

how can i convert a string ip address to a decimal number. 我如何将字符串ip地址转换为十进制数字。 eg I have a data bytes= b'363,3,1778952384,7076' , here 1778952384 is my ip address and 7076 is my port. 例如,我有一个数据字节= b'363,3,1778952384,7076' ,这里1778952384是我的IP地址,而7076是我的端口。 How can I convert my IP address to decimal number. 如何将我的IP地址转换为十进制数字。 below is my code, please help me to solve these problem 下面是我的代码,请帮助我解决这些问题

/app.py /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 has an ipaddress module which can handle this sort of thing. Python有一个ipaddress模块,可以处理这种事情。 It was added to the standard library in Python 3, but should be installable for earlier versions, too. 它已添加到Python 3的标准库中,但也应可安装在早期版本中。

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

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 : 您可能还会询问如何拆分字符串(在b','因为它是一个字节字符串),获取正确的字段并将其转换为int

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM