Separating IP nodes

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Tue Sep 5 04:47:55 EDT 2000


Kevin Breit wrote in comp.lang.python:
> Hey,
> 	In my app, I have a user enter an IP address.  Great.  Now, I want to 
> increment the last number.  For example:
> 1.1.1.1 becomes 1.1.1.2 (yes...thats an odd IP)
> What is the best way to separate that and increment only the last number?  
> I'm thinking some sort of regex, but not sure.  

The best way to parse the IP address is to use socket.inet_aton(); it's
provided by the OS, should do all the necessary error checking
(255.255.255.255 is not a valid address, for example), and
accept all the ways to write an IP address.

But unfortunately that doesn't give an integer, but a four byte string.
Now if we're lazy and assume that unsigned integers are 32-bit, we can
use struct.unpack on it to get something like this:

import socket, struct

def add_one_to_ip_addr(address):
   ip = struct.unpack('!I', socket.inet_aton(address))
   ip = ip+1
   return socket.inet_ntoa(struct.pack('!I', ip))

But if you're going to use this a long time you shouldn't be lazy and do
the unpacking by hand.

-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
  Murphy's Rules, "Does Dr. McCoy know?":
   FASA's Star Trek: The Role-Playing Game describes the Klingon Agonizer
   as hand-held device 'applied to the left shoulder just above where the
   ear is located in humans.'



More information about the Python-list mailing list