如何获取IP地址的国家/地区名称?

如何获取IP地址的国家/地区名称?

问题描述:

所以我发现这个网站是 http://ip-api.com/csv/208.80.152.201 [ ^ ]但事情就是一切都混合了。

我只想在成功之后获得国家名称。

关于如何做到这一点的任何想法?



我尝试过:



Dim client As WebClient = New WebClient()

Dim reply As String = client.DownloadString(http://ip-api.com/csv/208.80.152.201)

textbox1.Text = reply

So I found this website http://ip-api.com/csv/208.80.152.201[^] but the thing is everything's mixed.
I only want to get the country name after "success," word.
Any ideas on how to do this?

What I have tried:

Dim client As WebClient = New WebClient()
Dim reply As String = client.DownloadString("http://ip-api.com/csv/208.80.152.201")
textbox1.Text = reply

如果您查看api doc(对于csv) IP地理位置API - CSV [ip-api] [ ^ ]你会看到返回信息是


成功,国家,国家代码,地区代码,地区名称,城市,邮编CODE,LATITUDE,LONGITUDE,TIME ZONE,ISP NAME,组织名称,号码/名称,IP地址用于查询



所以,如果你做一个字符串.Split即



if you look at the api doc (for csv) IP Geolocation API - CSV [ip-api][^] you'll see that the return info is

success,COUNTRY,COUNTRY CODE,REGION CODE,REGION NAME,CITY,ZIP CODE,LATITUDE,LONGITUDE,TIME ZONE,ISP NAME,ORGANIZATION NAME,AS NUMBER / NAME,IP ADDRESS USED FOR QUERY

so, if you do a string.Split ie

char[] delimiterChars = { ',' };
String[] csvElements = reply.Split(delimiterChars);

string ipCountry = csvElements[1];











or

string ipCountry = csvElements[2];





IF csvElements [0] == 成功即



您可以将整个事物包装到一个函数中,传入int 1或2以查找您想要的哪个国家/地区版本,作为字符串,或者也许是string.Empty如果不是'成功'



这样的东西(未编译或测试)





IF csvElements[0] == "success" that is

You can wrap the whole thing into a function, pass in int 1 or 2 for 'which' country version you want back, returned as a string, or perhaps string.Empty if not 'success'

[edit] something like this (not compiled or tested)

static string getCountryFromReply(string reply, int countryVersion)
{
	if (!(reply.Trim().StartsWith("success")))
	{
		return string.Empty;
	}

	if (countryVersion != 1 && countryVersion != 2)
	{
		throw new argumentException("Only 1 or 2 Valid", "countryVersion");
	}

	char[] delimiterChars = {‘,’};
	string[] csvElements = reply.Split(delimiterChars);

	return csvElements(countryVersion);
}



[/ edit]



就是我想到的 - 你会需要重新输入它并仔细检查,来自我的Mac,VS可能会发誓你,但这就是要点 - 你也可以使countryVersion成为一个枚举,让它更容易记住,




[/edit]

is what I had in mind - you'll need to retype it though and check it carefully, the "" are from my Mac, VS will likely swear at you, but thats the gist - you could also make countryVersion an enum to make it easier to remember,

enum countryVersionReturn {countryLong=1, countryShort};





if你不喜欢这些,那么,你也可以看看只需要你想要的字段 IP Geolocation API - 返回值[ip-api] [ ^ ]在你的案例country,countryCode中,我不确定是否返回状态即成功/失败,我总是会包含状态字段,这意味着你仍然需要拆分字符串



if you dont like any of this, then, you can also look at just requesting the fields you want IP Geolocation API - Return values [ip-api][^] in your case country,countryCode, Im not sure if that returns the status ie success / fail, I would always include the status field anyway, which means you still have to split the string