Hi All,
Im working on a project for work, and part of this project is getting the IP from a host and translating it into Lattitude and Longitude(code for this is below). The problem I am facing currently is that when I try to get the IP, I get "::1" as my IP, which then gives me the Lat and Lon coordinates for some place in Hong Kong. What Can I Do to fix this? this is my first time programming something like this.
Thanks in Advance!
P.S to get the Lat and Lon I use GoogleMaps.LocationServices from NuGet.
Link: http://www.nuget.org/packages/GoogleMaps.LocationServices
Full Code:
using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Script.Serialization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using GoogleMaps.LocationServices;
namespace WebApplication3
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress))
{
ipAddress = Request.ServerVariables["REMOTE_ADDR"];
}
var locationService = new GoogleLocationService();
var point = locationService.GetLatLongFromAddress(ipAddress);
var latitude = point.Latitude;
var longitude = point.Longitude;
Lat.Text = latitude.ToString();
Lon.Text = longitude.ToString();
IP.Text = ipAddress;
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["testConnectionString1"].ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Observations(UserID, DateTime, Loc_Lat, Loc_Lon, Observation, Comments) VALUES (@UserID, @DateTime, @Loc_Lat, @Loc_Lon, @Observation, @Comments)", conn);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("@UserID", TextBox1.Text);
cmd.Parameters.AddWithValue("@Observation", TextBox2.Text);
cmd.Parameters.AddWithValue("@DateTime", DateTime.Now);
cmd.Parameters.AddWithValue("@Comments", TextBox3.Text);
cmd.Parameters.AddWithValue("@Loc_Lat", Lat);
cmd.Parameters.AddWithValue("@Loc_Lon", Lon);
conn.Open();
cmd.ExecuteNonQuery();
Response.Redirect("Webform1.aspx");
}
}
}
Section That concerns Lat/Lon and IP:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress))
{
ipAddress = Request.ServerVariables["REMOTE_ADDR"];
}
var locationService = new GoogleLocationService();
var point = locationService.GetLatLongFromAddress(ipAddress);
var latitude = point.Latitude;
var longitude = point.Longitude;
Lat.Text = latitude.ToString();
Lon.Text = longitude.ToString();
IP.Text = ipAddress;
}