[geek stuff] integer to ip address

Mai acu vreo saptamana asa, vine un gigel si intreaba pe NANOG cum poate converti un integer la o adresa IP, de exemplu din 1089055123 sa faca 64.233.169.147. trecand pe langa modalitatea matematica de a face aceasta conversie, o gramada de oameni au venit cu idei diferite despre cum poti realiza asta in diverse limbjae de programare, de la shell scripting la postscript. Enjoy!

bash

bash# inttoip(){ echo $[$1>>24].$[($1>>16)&255].$[($1>>8)&255].$[$1&255]; }
bash# inttoip 1089055123
64.233.169.147

bc

$ bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty’.
obase=256
1089055123

064 233 169 147

shell

# ping -c 1 1089055123 | head -n 1 | awk ‘{{{print $3}}}’ | sed ‘s/((.*))/1/’
64.233.169.147

REXX

PARSE VALUE D2X(ARG(1)) WITH a 3 b 5 c 7 d .
SAY X2D(a)”.”X2D(b)”.”X2D(c)”.”X2D(d)

PHP

echo long2ip(‘1089055123’);

C

#include <stdio.h>
main(int argc, char *argv[])
{
union {
unsigned int i;
unsigned char c[4];
} ip;
int i = 0;
ip.i = 1089055123;
/* endian-neutral iteration: */
printf(“%d.%d.%d.%dn”, ip.c[i++], ip.c[i++], ip.c[i++], ip.c[i++]);
return 0;
}

Perl (two liner)

sub ntoa_in_one_line { join(“.”, unpack(“CCCC”, pack(“N”, $_[0]))); }
print ntoa_in_one_line(1089055123) . “n”;

awk

dec2ip
awk ‘{ print int($1 / 16777216) “.” int($1 % 16777216 / 65536) “.” int($1 % 65536 / 256) “.” int($1 % 256) }’

ip2dec
awk ‘{ split($1, a, “.”); print a[1]*16777216 + a[2]*65536 + a[3]*256 + a[4] }’

Ruby

require “ipaddr”
print “#{IPAddr.new(167772215,Socket::AF_INET)}n”

Perl (one liner)

$ perl -e ‘use IO::Socket; print inet_ntoa(pack(“N”,2066563929)).”n”;’
123.45.67.89

ITS TECO

1089055123u14<q1&377.j46i0jq1/400.u1>d$$

PostScript (in cazul in care vreti sa faca imprimanta calculele)

##### BEGIN of ntoa.ps #####
%!
/ntoa {
3 { dup 256 idiv exch 256 mod exch } repeat 256 mod
} def

/printa {
3 string cvs show 3 { (.) show 3 string cvs show } repeat
} def

/Helvetica findfont 36 scalefont setfont 36 444 moveto

1089055123 ntoa printa

showpage
###### END of ntoa.ps ######

Fun, ain’t it, no ?

One thought on “[geek stuff] integer to ip address

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.