How to determine a zip code and city from an IP address? [closed]

血红的双手。 提交于 2019-11-26 18:27:13

What I use is ip2nation: http://www.ip2nation.com

It is a completely free MySQL database of IP to country mappings. They include a few sample PHP scripts at their site.

I use it on my WordPress blog along with Ozh's free IP to Nation WordPress Plugin

Even if you are not using WordPress, download the plugin as it will give you a good set of PHP code to access the database with. He even has a nice set of tiny country flags that you can display next to, or instead of the country name, which is what I do to automatically show flags next my blog's commenter's names.

Really, you don't need an API for this. All you need is the database and an ability to write the PHP and SQL code to access it.

I wouldn't recommend ip2location for casual use. They charge a lot for their databases, and their databases are very large, and have more detail than most people need.

But ip2nation only goes to the Country level. If you do need Cities and Zipcodes (despite the fact that they can be wrong as other answers/comments have stated), then in addition to ip2location, you can try GeoBytes. They have components specifically suited for geo-specific web site content, such as GeoSelect: http://www.geobytes.com/GeoSelect.htm

Also search for "ip to zipcode" on Google.

Best (meaning easy to integrate and free) way I've found is available here. The service is completely free, doesn't require any local installations and doesn't force you to put banners on your site (as opposed to IP2Location). The only restriction they have, the query limit, is very reasonable: you can fire a query every 2 seconds, and even if you make more frequent queries, you'll get the results just a bit slower. Enjoy!

Kapil

I hope All the users, who wants to fetch location from IP address, will get a proper solution with using this small code.

$ip_addr = $_SERVER['REMOTE_ADDR'];
$geoplugin = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip_addr) );

if ( is_numeric($geoplugin['geoplugin_latitude']) && is_numeric($geoplugin['geoplugin_longitude']) ) {
    $lat = $geoplugin['geoplugin_latitude'];
    $long = $geoplugin['geoplugin_longitude'];
}

Geocoder.ca gives a lot of info for ip addresses (North America Only) eg, http://geocoder.ca/99.229.2.190?geoit=xml (also supports geoit=json and jsonp)

<result>
<geodata>
  <latt>43.623262</latt>
  <longt>-79.749543</longt>
  <city>MISSISSAUGA</city>
  <prov>ON</prov>
  <postal>L5N7Z9</postal>
  <stnumber>1837</stnumber>
  <staddress>Samuelson CIR</staddress>
  <TimeZone>America/Toronto</TimeZone>
  <AreaCode>289</AreaCode>
  <confidence>1</confidence>
  <intersection>
    <street1>Samuelson Cir</street1>
    <street2>Stockbridge Crt</street2>
    <lattx>43.622696</lattx>
    <longtx>-79.748706</longtx>
    <city>MISSISSAUGA</city>
    <prov>ON</prov>
    <distance>0.179</distance>
  </intersection>
 </geodata>
 </result>

The following is a modified version of a snippet I found that uses http://ipinfodb.com/ip_locator.php to get its information. Keep in mind, you can also apply for an API key with them and use the API directly to get the information supplied as you see fit. As you can see http://ipinfodb.com/ip_location_api.php, they have examples in everything from PHP to JavaScript, to ASP.Net. As noted, below does not require a key as it pulls their public page and Regex's through the page to get specified info. Key's are free.

Snippet

function detect_location($ip=NULL, $asArray=FALSE) {
    if (empty($ip)) {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }
        else { $ip = $_SERVER['REMOTE_ADDR']; }
    }
    elseif (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost') {
        $ip = '8.8.8.8';
    }

    $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
    $i = 0; $content; $curl_info;

    while (empty($content) && $i < 5) {
        $ch = curl_init();
        $curl_opt = array(
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_HEADER => 0,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_URL => $url,
            CURLOPT_TIMEOUT => 1,
            CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
        );
        if (isset($_SERVER['HTTP_USER_AGENT'])) $curl_opt[CURLOPT_USERAGENT] = $_SERVER['HTTP_USER_AGENT'];
        curl_setopt_array($ch, $curl_opt);
        $content = curl_exec($ch);
        if (!is_null($curl_info)) $curl_info = curl_getinfo($ch);
        curl_close($ch);
    }

    $araResp = array();
    if (preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs)) $araResp['city'] = trim($regs[1]);
    if (preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs)) $araResp['state'] = trim($regs[1]);
    if (preg_match('{<li>Country : ([^<]*)}i', $content, $regs)) $araResp['country'] = trim($regs[1]);
    if (preg_match('{<li>Zip or postal code : ([^<]*)</li>}i', $content, $regs)) $araResp['zip'] = trim($regs[1]);
    if (preg_match('{<li>Latitude : ([^<]*)</li>}i', $content, $regs)) $araResp['latitude'] = trim($regs[1]);
    if (preg_match('{<li>Longitude : ([^<]*)</li>}i', $content, $regs)) $araResp['longitude'] = trim($regs[1]);
    if (preg_match('{<li>Timezone : ([^<]*)</li>}i', $content, $regs)) $araResp['timezone'] = trim($regs[1]);
    if (preg_match('{<li>Hostname : ([^<]*)</li>}i', $content, $regs)) $araResp['hostname'] = trim($regs[1]);

    $strResp = ($araResp['city'] != '' && $araResp['state'] != '') ? ($araResp['city'] . ', ' . $araResp['state']) : 'UNKNOWN';

    return $asArray ? $araResp : $strResp;
}

To Use

detect_location();
//  returns "CITY, STATE" based on user IP

detect_location('xxx.xxx.xxx.xxx');
//  returns "CITY, STATE" based on IP you provide

detect_location(NULL, TRUE);    //   based on user IP
//  returns array(8) { ["city"] => "CITY", ["state"] => "STATE", ["country"] => "US", ["zip"] => "xxxxx", ["latitude"] => "xx.xxxxxx", ["longitude"] => "-xx.xxxxxx", ["timezone"] => "-07:00", ["hostname"] => "xx-xx-xx-xx.host.name.net" }

detect_location('xxx.xxx.xxx.xxx', TRUE);   //   based on IP you provide
//  returns array(8) { ["city"] => "CITY", ["state"] => "STATE", ["country"] => "US", ["zip"] => "xxxxx", ["latitude"] => "xx.xxxxxx", ["longitude"] => "-xx.xxxxxx", ["timezone"] => "-07:00", ["hostname"] => "xx-xx-xx-xx.host.name.net" }

In Ruby...These are the steps

  1. Install gem geocoder gem install geocoder
  2. In a ruby script,have these lines.

    require "geocoder"

    puts Geocoder.address('76.95.251.102'); // Change the ip address accordingly.

  3. Run the script to get the city, state, zipcode, Country

output: Bellflower, CA 90706, United States

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!