0

クライアントのIPを文字列として返すgetIP()という名前のメソッドがあります。

このIPを使用して、このサービスを使用しているクライアントの場所を取得するにはどうすればよいですか。

これは私がクライアントのIPアドレスを表示する方法です。

string IP = getIP();
lblIPAddress.Text = "IP " + IP;

クライアントの場所をに含めるにはどうすればよいですか?

i.e. lblIPAddress.Text = "IP " + IP+ "location" ;)  
4

1 に答える 1

2

以下に、そのAPIのXMLエンドポイントからデータを取得するために使用していた非常に単純なスニペットを示します(APIに変更はなかったため、引き続き機能するはずです)。

string city;
string country;
string countryCode;
decimal longitude;
decimal latitude;

XmlTextReader hostIPInfoReader = new XmlTextReader("http://api.hostip.info/?ip=" + IP);
while (hostIPInfoReader.Read()) {
    if (hostIPInfoReader.IsStartElement()) {
        if (hostIPInfoReader.Name == "gml:name")
            city = hostIPInfoReader.ReadString();

        if (hostIPInfoReader.Name == "countryName")
            country = hostIPInfoReader.ReadString();

        if (hostIPInfoReader.Name == "countryAbbrev")
            countryCode = hostIPInfoReader.ReadString();

        if (hostIPInfoReader.Name == "gml:coordinates") {
            string[] coordinates = hostIPInfoReader.ReadString().Split(new char[] { ',' });
            longitude = decimal.Parse(coordinates[0]);
            latitude = decimal.Parse(coordinates[1]);
        }
    }
}

このコードはもちろん改善することができますが、それはあなたにとって良い出発点であると私は信じています。

于 2012-09-11T11:45:11.543 に答える