Converting a decimal number to ip address in python

So, I was messing around with something tonight where I needed to get the ip address of a machine from decimal format into the traditional string as we know it. Now, an ip address is literally just a 32 bit number really, and thus the ip address. 192.168.0.1 converts into 11000000101010000000000000000001 in binary, or 3232235521 in decimal.

So just how do we go about converting this. Well for most of you this is going to be easy, but I for one had never messed with binary data much before in python and so I thought I would give this a try.

My code below works around two loops, one nested inside the other. Why you ask? Well, we need to eventually get 4 numbers out of this, to make up our, w.x.y.z format. Since each octet is 8 bits long, 32 / 8 = 4. Man I can’t remember the last time maths was that easy.

So we loop through the outer loop 4 times. The inner loop, 8 times. This is because we are actually recreating the binary notation from the decimal, splitting the decimal into 4 distinct 8bit binary numbers. I could have gotten the whole number out as a 32bit value and padded it with zeros on the front if it didn’t quite hit 32 bits and then use some fancy string manips to pull out 8 characters at a time.

I didn’t want to do it that way though 🙂 This way we get to learn about a cool operator in python, two in fact. As we step through the first loop we immediately come to a second, where you see the line ip1=str(ipint % 2)+ip1

So what does this actually do. Well most of it should be familiar to you. The only bit which may cause a question is the % operator. It’s called the modulus operator. Basically it divides the first number by the second and gives us what’s left over, instead of giving us a decimal figure. Whenever we calculate the modulus of a number against the value of 2, we can only have one of two possibly outcomes, either the number is even or odd, so the leftover is either 1 or 0. In essence that tells us the last “bit” of the binary number. So we add that to a string, making sure we put it at the right hand end.

Next we need to look at the next bit. We do this by using the >> operator. This shifts the bit one position to the right, essentially making the number one bit smaller and chopping off the last bit that we have just identified using the modulus function.

We continue this procedure 8 times, building up a string, which will contain the binary representation of our last octet. We then add that to another string using the int(ip1,2) command, which turns the binary back into a decimal. We’ve then hit the end of our inner loop. We continue this for three more times, and at the end we print out our final ip address.

Simple really.

ipint = 3232235521
ip=""
for i in range(4):
        ip1 = ""
        for j in range(8):
                print ipint % 2
                ip1=str(ipint % 2)+ip1
                ipint = ipint >> 1
                print ip1
        print ip1
        ip = str(int(ip1,2)) + "." + ip
print ip.strip(".")

Advertisement

Blogging, feedback and the new video show

I often wondered what it would be like to run a blog without the huge backing and publication that I used to enjoy from planet Ubuntu. It certainly feels different. It feels like I’m talking to a much more direct audience, talking to people who I hope want to be reading this blog. Though some of my posts on my blog on planet Ubuntu used to rake in a large number of views, it’s much nicer now to know that the people reading the geekdeck blog have come here of their own accord.

It seems to have given me more confidence to write again too. As I said, previous energies were drained in the great book writing of 09 🙂 But now I feel ready to blog again. You should start to see more technical posts from me, instead of these ramblings, but I hope you still enjoy it nonetheless.

The video project has a name now, codenamed ‘geekdeck mini’. I am trying desperately to get the intro video together. I only want it to be 10 seconds maximum, just really short, but it’s hard. Video creation isn’t my strong point. If anyone has any ideas, please let me know.

It feels good to be blogging

It certainly does feel good to be blogging again. I have many new things I’ve learnt, that I’d love to share with you. I’ll hopefully be starting up the new mini video series soon too. It’s going to take a little time to get it started, but once it’s there, it should be awesome. I really hope you all enjoy reading the posts here on geekdeck. It’s been a long time since I’ve had the time and the inclination to blog. So much of my writing energies were taken up with Emblem Divide. Now I’m back. Bigger and better than before 🙂

Learning Assembler: The easy way!

Well, I’ve finally succumbed to the pressure from…..well…me. As many of you know, I’m interested in the world of security and I thought one way to take this to a new level would be to learn the language of the shellcode, Assembler. For those of you who think I’m being vague, I’m talking about x86 ASM. I want to be able to look at a piece of shellcode and even some malware, and understand what at least part of it means.

So just how do you go about learning assembler? It’s probably one of the most difficult languages to learn. It is the lowest level of computer programming, other than dealing directly in Machine Code (not pretty). I’m not going to delve into the details of what I’ve learnt so far, but I do want to shout out to the great resource which has made learning Assembler possible for me. Security Tube has some awesome tutorial videos. In particular, this series, really takes you through learning Assembler in a simple and structured manner. I’m far from finished with this topic, but I’m getting there slowly.

Encoding Video for Cell Phones

Recently as many of you will know, I managed to get rid of the ridiculously appalling Skype S2 Phone, and replace it with a cheap, but very functional Sony Ericsson T715. Now, I’m not going to get into the various merits of each, suffice to say the SE has a decent resolution screen, at 320×240 and can handle a variety of video formats.

Right I said to myself, time to start a new project. The basic idea is this, I wanted to record a short video cast series using just my cell phone and a laptop. It seems doable. It seems reasonable. Yet I have to say I have come across my fair share of issues.

The premise for this video cast is that all “live” video has to be recorded on the phone itself. Screencasts are allowed and initially I wanted all editing to be done on my aging X41 laptop. More on this later. The first task was to get a video from my desktop in a format that the phone did not recognise, and convert it for use on the phone. A quick examination of the format the phone used led me to believe it was an MP4.

This is where video editing and encoding gets a little more complicated. You see, when you being looking at video files you will notice there are many types of files, MP4, WMV, 3GP, MOV, AVI etc. One would assume that if you can get a file from AVI to MP4 for example, that it would play perfectly well on the phone. Wrong.

You see the file formats are merely “containers”. In fact, that’s what they are called, “container formats”. They define a method for linking together and storing the audio and the video in a single file. The problem is that inside this “container” the audio and video can be stored in several different formats for each container.

A great tool, called mediainfo, is able to show you exactly what formats are stored inside each file to allow you to try and replicate this. The trick was to take a video created by the phone, and run it through mediainfo. I ended up with a listing, similar to this.

pete@satsuki:~/Videos$ mediainfo MOV00183.MP4
General
Complete name                    : MOV00183.MP4
Format                           : MPEG-4
Format profile                   : 3GPP Media Release 5
Codec ID                         : 3gp5
File size                        : 10.5 MiB
Duration                         : 2mn 5s
Overall bit rate                 : 704 Kbps
Encoded date                     : UTC 2010-01-07 09:09:15
Tagged date                      : UTC 2010-01-07 09:09:15

Video
ID                               : 1
Format                           : MPEG-4 Visual
Format profile                   : Simple@L4a
Format settings, BVOP            : Yes
Format settings, QPel            : No
Format settings, GMC             : No warppoints
Format settings, Matrix          : Default (H.263)
Codec ID                         : 20
Duration                         : 2mn 5s
Bit rate mode                    : Variable
Bit rate                         : 671 Kbps
Nominal bit rate                 : 768 Kbps
Maximum bit rate                 : 1 536 Kbps
Width                            : 320 pixels
Height                           : 240 pixels
Display aspect ratio             : 4:3
Frame rate mode                  : Variable
Frame rate                       : 14.651 fps
Minimum frame rate               : 13.514 fps
Maximum frame rate               : 15.873 fps
Resolution                       : 8 bits
Scan type                        : Progressive
Bits/(Pixel*Frame)               : 0.596
Stream size                      : 10.0 MiB (95%)
Language                         : Japanese
Encoded date                     : UTC 2010-01-07 09:09:15
Tagged date                      : UTC 2010-01-07 09:09:15

Audio
ID                               : 2
Format                           : AAC
Format/Info                      : Advanced Audio Codec
Format version                   : Version 4
Format profile                   : LC
Format settings, SBR             : No
Codec ID                         : 40
Duration                         : 2mn 5s
Bit rate mode                    : Variable
Bit rate                         : 31.1 Kbps
Nominal bit rate                 : 32.0 Kbps
Maximum bit rate                 : 64.0 Kbps
Channel(s)                       : 1 channel
Channel positions                : C
Sampling rate                    : 16.0 KHz
Stream size                      : 475 KiB (4%)
Language                         : Japanese
Encoded date                     : UTC 2010-01-07 09:09:15
Tagged date                      : UTC 2010-01-07 09:09:15

During my initial tests, I had wrongly assumed that the MP4 would be using the MPEG video format. When in fact, you can see above, it actually uses 3GP. After some tinkering, and a great deal of help from the #ffmpeg IRC channel, I can now present an ffmpeg line which gets me a MP4 playable file on my SE T715 phone.

/usr/bin/ffmpeg -i -f 3gp -vcodec mpeg4 -s 320x240 -g 250 -qscale 4 -mbd rd -trellis 1 -subcmp satd -acodec libfaac -ab 112kb -ar 16000 -ac 2

My troubles didn't end there, but I won't delve into those right now. Suffice to say I have had a nightmare getting videos to go into the editing software in "sync". I finally have a formula though and hopefully we'll be seeing the first episode very shortly.

Bluetooth Remote Control – Awesome Technology

A few years ago I bought a Sony Ericsson w810i and absolutely loved it. A lesser known feature at the time was the bluetooth remote control functionality which allowed you to control your PC via your cell phone. Pointless? Well, not entirely. The people at Sony had built 3 profiles. They were Media Player, Presenter and Desktop. Within these they had setup nominal key bindings for the task in question. This meant that clicking the right button on the phone for example, would click the left mouse button, advancing through a slide show.

I moved voice networks a little while back and was landed with a truly awful phone, more on that in another post. Consequently, just recently I managed to afford another Sony Ericsson, this time, a T715. To my delight, the remote control functionality was still there. After some google searching I came across this little gem of a page.

Armed with this, it seems we can control any application we like, and map certain keys to the cell phones keypad. The real question is, how can we make use of such technology beyond the obvious. There are already bindings for things like Media Players etc. Is there anything else we can use this for? I was toying with the idea of a little voice activated app that would tell me certain information audibly, when I pressed a certain button. New Emails, new IMs….that kind of thing. However it seems just that little bit lame. Anyone got any better ideas?

Change Management at home?

I never thought it would be as bad at home as in some corporate environments, but for the past two weeks I have been fighting with the main user in my house for 15 minutes of downtime on the server to install a third network card. I joked that it felt like I should be filing a Change Management request form.

Today I finally got the opportunity to install the card and so begins my foray into VLANs on Linux. I’m hooking up a WAP with triple SSIDs, which are separated via VLAN tags, to try to a) segregate the network a little better, and b) add a little more robustness to the setup.

Stay tuned to find out how I get on.

A fresh new start

OK, so with GeekDeck, I was trying to achieve something big, I was trying to break all the rules, do something completely different. Only problem was a) it had all been done before and b) I was trying to make it too big too soon, with too few resources. I am eternally grateful to each of the contributors for the time and effort that they put into GeekDeck. Now it’s time for something a little different.

I’ve not blogged properly for a long time and I must say it’s been itching away at me for many an hour of many a day. I love blogging. I love sharing things with communities. I loved my time in the ubuntu community and being aggregated on planet ubuntu gave me a platform on which I could share my ideas and feelings with a large audience.

GeekDeck was my attempt to take this one further, but I made the mistake of biting off far more than I could chew. My friends and contributors did the best they could in providing me with material, but I neglected to take into account their work loads and consequently ended up writing many more articles than I would have liked. I say would have liked, but that’s not quite accurate. I enjoy writing, but I was being pushed to write 7-8 well researched 1,500 – 2,000 word articles a month. It was hard work.

It was only recently that I took a peek at the statistics on GeekDeck, and realised that actually we still have a fair old number of people visiting the site. To that end, I decided to move the focus of GeekDeck. Any of the contributors are free to blog here about things that interest them in the technical/geek world.

So enjoy as we take GeekDeck on a whole new journey 🙂

Pete

Editor’s Letter : We’ve come a long way in a short time

Hi geeks

Well, we’ve made it to issue 3, I know there were some of you out there thinking we couldn’t do it. Go on fess up 🙂 To be honest it’s not been entirely easy, but the team are working so hard to bring you each new issue. This one should be a really good issue, we have a fantastic interview with the OpenCandy CEO, plus a feature on Creating your very own Live CD distro and many more articles covering; undo, geeks and the Internet. We’ve also hopefully got the first GeekDeck podcast coming out in a few days. It’s a musing on many things, covering; Piracy, Marios Moustache, HUDs, Bugs, and much much more.
Continue reading

Review : Cherry Picks of the Month: Foresight Linux

OgI just cannot believe that it has been a month to the day that I proudly signed off on the Cherry Pick of the Month for the second issue of GeekDeck! A whole lot has happened since then and I literally did not have a chance to get a lot of writing done. As if keeping up and committing translations for the GNOME, Xfce and LXDE projects wasn’t enough, I embarked on a 2-week-long roller coaster of a ride at work that just ended this afternoon! Have I mentioned that I am also running for the GNOME Board of Directors? My last adventures took me to a very familiar road, this time in my own backyard so to speak, as I was elected into the Foresight Linux Council and became their Community Manager.
Continue reading

Interview : OpenCandy CEO Darrius Thompson

darriusOpenCandy (www.opencandy.com) is a startup from San Diego, California that allows software publishers to connect and recommend other pieces of software during the installation of their product. It allows independent software makers to create distribution revenue while maintaining a good relationship with their users or simply to recommend other pieces of free software that they like.

How did you guys come up with the idea for OpenCandy?

We were looking for a problem to solve that we would be passionate about, that would leverage our past successes, and that had a good probability of getting us to self sustainment in a reasonable amount of time.
Continue reading