python换字符串位置_如何在python中将字符串转换为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 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'

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]))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值