I need a working detection of country script
#10

This whole thing can be done so much easier:

pawn Code:
//Get IP and send that data:
new string[45];
GetPlayerIp(playerid, string, 16);
format(string, sizeof(string), "ip-api.com/csv/%s?fields=3", string);
HTTP(playerid, HTTP_GET, string, "", "OnLookupIP");

//Retrieve the data:
foward OnLookupIP(index, response_code, data[]);
public OnLookupIP(index, response_code, data[]) //Not checking if response was OK (200) here
{
    new Country[64], cCode[2];
    sscanf(data, "p<,>s[64]s[2]", Country, cCode);
    //Now you know the country (Country) and country code (cCode) of "index" (index = playerid)
}
http://ip-api.com/csv/IP_HERE?fields=3 returns nothing but: Country,Country_Code. If you just need the country name, use ?fields=1. Then you won't even need sscanf and you can just use "data".

NOTE: HTTP() is threaded. So if you want to retrieve the country before doing anything else (such as checking if the player is registered) you should use this under OnPlayerConnect as the very first thing, and proceed once the data comes in at OnLookupIP().

EDIT:
If you want to fetch all data like in the post above, you should use ip-api.com/csv/IP_HERE (without ?fields=x)
This returns (if success):
Code:
success,COUNTRY_NAME,COUNTRY_CODE(2 chars),REGION_CODE(2 chars),REGION_NAME,CITY,LAT,LON,TIMEZONE,ISP,ORG,AS,QUERY(which is the IP)
If it failed (eg. by using a local IP):
Code:
fail,message,query
'message' in such a case would be "private range" or "reserved range" if you're connecting as localhost (127.0.0.1)


Since the /csv/ returns the data seperated by comma's you won't need multiple kind of functions to fetch the data, you can simply use sscanf. Example:
pawn Code:
//Get IP and send that data:
new string[37];
GetPlayerIp(playerid, string, 16);
format(string, sizeof(string), "ip-api.com/csv/%s", string);
HTTP(playerid, HTTP_GET, string, "", "OnLookupIP");

foward OnLookupIP(index, response_code, data[]);
public OnLookupIP(index, response_code, data[])
{
    new success[8], Country[64], cCode[2], rCode[2], Region[64], City[64], Float:gps_lat, Float:gps_lon, timezone[64], IspName[64], IspOrg[64], AS[10];
    sscanf(data, "p<,>s[8]s[64]s[2]s[2]s[64]s[64]ffs[64]s[64]s[64]s[10]", success, Country, cCode, rCode, Region, City, gps_lat, gps_lon, timezone, IspName, IspOrg, AS);
}
If success is "fail", use "Country" to get the message error.
Note how I by default used array sizes of 64 cells. No idea what maximum names can be for regions, ISP, cities etc. Might wanna tweak it a bit if it turns out they're too small or too big.
Reply


Messages In This Thread

Forum Jump:


Users browsing this thread: 1 Guest(s)