16

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?

Example: From 192.168.1.1 to 11000000.10101000.00000001.00000001

4
  • Are you looking to convert an IPv4 Address into its integer representation? Or what binary representation are you trying to convert to? Commented Apr 28, 2010 at 23:28
  • 1
    Example: From 192.168.1.1 to 11000000.10101000.00000001.00000001 Commented Apr 28, 2010 at 23:35
  • That is an extremely uncommon way to express ipaddresses. I don't think any module exists to produce or consume that format. Commented Apr 29, 2010 at 0:00
  • 1
    The way you are thinking of is perfectly good and efficient enough, IMHO. Commented Apr 29, 2010 at 0:24

8 Answers 8

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That's what I was looking for but, I don't fully understand how it works. I get that you are splitting the ip address by '.', then joining the results by a '.', and converting from a integer to binary but this: "(x)+256)[3:] for x in", completely lost. Can you point in the right direction to look up what you are doing?
@pizzim13: no magick. You understood well how it works. The +256 is there to always have a 9 bits binary number, then it's easy to remove 0b1 at front of the number.
@pizzim13: and for the [... for x in ... ] part look at list comprehension in python documentation.
9

Is socket.inet_aton() what you want?

1 Comment

It seems to work: bin(struct.unpack('!I', socket.inet_aton('192.168.1.1'))[0]) -> '0b11000000101010000000000100000001'
9

Purpose being to later calculate the broadcast address for Wake on LAN traffic

ipaddr (see PEP 3144):

import ipaddr

print ipaddr.IPNetwork('192.168.1.1/24').broadcast
# -> 192.168.1.255

In Python 3.3, ipaddress module:

#!/usr/bin/env python3
import ipaddress

print(ipaddress.IPv4Network('192.162.1.1/24', strict=False).broadcast_address)
# -> 192.168.1.255

To match the example in your question exactly:

# convert ip string to a binary number
print(bin(int(ipaddress.IPv4Address('192.168.1.1'))))
# -> 0b11000000101010000000000100000001

Comments

3

You can use string format function to convert the numbers to binary. I made this function:

def ip2bin(ip):
    octets = map(int, ip.split('/')[0].split('.')) # '1.2.3.4'=>[1, 2, 3, 4]
    binary = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(*octets)
    range = int(ip.split('/')[1]) if '/' in ip else None
    return binary[:range] if range else binary

This will return a binary IP or IP range, so you can use it to test if an IP is in a range:

>>> ip2bin('255.255.127.0')
'11111111111111110111111100000000'
>>> ip2bin('255.255.127.0/24')
'111111111111111101111111'
>>> ip2bin('255.255.127.123').startswith(ip2bin('255.255.127.0/24'))
True

Comments

1

Define IP address in variable

ipadd = "10.10.20.20"

convert IP address in list

ip = ipadd.split(".")

Now convert IP address in binary numbers

print ('{0:08b}.{1:08b}.{2:08b}. 
    {3:08b}'.format(int(ip[0]),int(ip[1]),int(ip[2]),int(ip[3])))

00001010.00001010.00010100.00010100

Comments

1
IP = '192.168.1.1'

ip2bin =  ".".join(map(str,["{0:08b}".format(int(x)) for x in IP.split(".")]))
print(ip2bin)

output

11000000.10101000.00000001.00000001

Comments

1

Should I be looking at netaddr, sockets, or something completely different?

For anyone asking in the present day, you should use netaddr if you want to do anything not supported in the Python 3.3+ built-in ipaddress module. Here is how you would do what you wanted to with netaddr, as an example:

>>> from netaddr import IPAddress
>>> ip = IPAddress('192.168.1.1')
>>> print(ip.bits())
11000000.10101000.00000001.00000001

Comments

0

ip = '192.168.1.1'

k=[" "]

for x in ip.split("."):

   a=(bin(int(x))[2:])
   k.append(a)    

print(".".join(list(k))[2:])

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.