Web Hosting Info

Search:

featured partner

The IP to Country Database

  Forum Topics : Development / Util for converting IP numbers to dot quaded address
Submitted by gromit on Mon, 06/20/2005 - 12:29.
I wanted the ips in standard format and tried to do this in PHP. It turns out PHP's bitwise operations are broken or do not work as I would expect so couldn't do it. I ended up writing (and learning) this in C which is now callable from php C code is here
/* ConvertIP By K Gray
 * Written 20/06/2005 cause I cannot do it in PHP
*/

#include 
#include  

main (argc, argv)
/*Converts decimalip to properip*/
int argc;
char *argv[];
{
        unsigned int dec;
        unsigned int oct1, oct2, oct3, oct4;
       if (argc != 2) {
                fprintf(stderr, "Usage: %s DecIP\n", *argv);
                exit(1);
                }
        dec=strtol(argv[1],NULL,10 );
        oct1=dec & 0xff;
        oct2=(dec>>8) & 0xff;
        oct3=(dec>>16) & 0xff;
        oct4=(dec>>24) & 0xff;
        printf ("%d.%d.%d.%d\n",oct4,oct3,oct2,oct1);
        }
################################################################################
To compile
cc convip.c -o convertip


To call it from php you can use the exec function like this
#!/usr/bin/php -q
<script language="php">

#usual open file read and explode by line etc etc etc
#dummy value used for test purposes here
$ip = 33996344;
exec ("./convertip $ip",$result);
echo $result[0]."\n";

Please accept my apologies if the C code is not very good as I had to teach myself as I went along. finding out about strtol call was a pain :-/ Cheers Karl
Comment viewing options:
Select your preferred way to display the comments and click 'Save settings' to submit your changes.
Optimization
Posted by Kaika on Sun, 09/17/2006 - 07:28.
this code is not optimal:

dec=strtol(argv[1],NULL,10 );
oct1=dec & 0xff;
oct2=(dec>>8) & 0xff;
oct3=(dec>>16) & 0xff;
oct4=(dec>>24) & 0xff;
printf ("%d.%d.%d.%d\n",oct4,oct3,oct2,oct1);

this code is better:

DWORD DW = strtol(argv[1],NULL,10 );
BYTE *b = (BYTE*)&DW;
printf ("%d.%d.%d.%d\n",b[3],b[2],b[1],b[0]);

it is very simple and work very fast :)

I use this cide in my utility:
http://rembo.game-host.org/downloads/IPCountry.zip