在Python中将IP地址字符串转换为二进制 [英] Convert IP address string to binary in Python

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

问题描述

作为更大的应用程序的一部分,我试图将IP地址转换为二进制。目的是稍后计算LAN唤醒流量的广播地址。我假设有一种更有效的方法来做到这一点,然后我的思维方式。这是通过八位字节分解IP地址,在必要时将0添加到每个八位字节的开头,将每个八位字节转换为二进制,然后组合结果。我应该查看netaddr,套接字还是完全不同的东西?

As part of a larger application, I am trying to convert an IP address to binary. Purpose being to later calculate the broadcast address for Wake on LAN traffic. I am assuming that there is a much more efficient way to do this then the way I am thinking. Which is breaking up the IP address by octet, adding 0's to the beginning of each octet where necessary, converting each octet to binary, then combining the results. Should I be looking at netaddr, sockets, or something completely different?

示例:从192.168.1.1到11000000.10101000.00000001.00000001

Example: From 192.168.1.1 to 11000000.10101000.00000001.00000001

推荐答案

你想到类似下面的东西?

You think of something like below ?

ip = '192.168.1.1'
print '.'.join([bin(int(x)+256)[3:] for x in ip.split('.')])

我同意其他人的意见,你可能应该避免转换为二进制表示来实现你想要的目标。

I agree with others, you probably should avoid to convert to binary representation to achieve what you want.

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

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