Link to home
Start Free TrialLog in
Avatar of Panos
PanosFlag for Germany

asked on

IP Address to Country in Coldfusion

Hello experts.
I'm trying to use this php tutorial:https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_3437-IP-Address-to-Country-in-PHP.html

I added the data into my db. and i need a little help now with the second code (step 4) .
The question is what are these two lines doing:
// IP ADDRESSES ARE UNSIGNED AND MAY RETURN NEGATIVE VALUES
$ip_number = sprintf('%u', $x);

My code is working but i did't add the function above for negative values and the validation.
Any help to complete it?
<cfscript>
/**
* Generates an (IPv4) Internet Protocol dotted address (aaa.bbb.ccc.ddd) from the proper address representation. Returns 0 if error occurs.
*
* @param longip Numeric value of the address you want to convert. (Required)
* @return Returns a String.
* @author Troy Pullis (tpullis@yahoo.com)
* @version 1, Jan 5, 2009
*/
function long2ip(longip)
{
   var ip = "";
   var i = "";
if (longip < 0 || longip > 4294967295)
      return 0;
for (i=3;i>=0;i--) {
ip = ip & int(longip / 256^i);
longip = longip - int(longip / 256^i) * 256^i;
if (i>0)
         ip = ip & ".";
}
return ip;
}

/**
* Converts a string containing an (IPv4) Internet Protocol dotted address (aaa.bbb.ccc.ddd) into a proper address representation. Returns 0 if error occurs.
*
* @param ip Dotted address value you want to convert. (Required)
* @return Returns a String.
* @author Troy Pullis (tpullis@yahoo.com)
* @version 1, Jan 5, 2009
*/
function ip2long(ip) {
   var iparr = ListToArray(ip,".");
   if (ArrayLen(iparr) != 4)
      return 0;
   else
       return iparr[1]*256^3 + iparr[2]*256^2 + iparr[3]*256 + iparr[4];
}
</cfscript>
<!--- <cfset myip = CGI.REMOTE_ADDR /> --->
<cfset myip = '85.75.31.212'/>
<cfset myip2long = ip2long(myip) />
<!--- <cfdump var="#myip2long#"> --->
<cfquery name="getcountry" datasource="#request.dsn#">
SELECT country_code, country_name FROM ip2country WHERE #myip2long# BETWEEN ip_number_lo AND ip_number_hi LIMIT 1
</cfquery>
<cfdump var="#getcountry#">

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of _agx_
_agx_
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Panos

ASKER

Thank you agx.
Avatar of Panos

ASKER

Thank you very much
regards
panos
Hm.. in that thread are they saying that "%u" just removes the sign from an integer?  I think so, but the reason for asking is that some languages like java have the concept of signed/unsigned types.  Converting from one to the other does more than just drop the sign.  (So I want to be sure the answer I gave you is correct)