How to Get IPAddress when User open web site using IP Address? - c#

I am generating run time <a> link. To complete link I am using bellow code:
string appPath = protocol + System.Web.HttpContext.Current.Request.ServerVariables["HTTP_HOST"] + System.Web.HttpContext.Current.Request.ApplicationPath;.
But when user try to open web site from: http://123.123.123.123/testApp at this time my link is created with http://myservername.com/testApp.
I want the address what ever user enter.
If user Open open website from http://123.123.123.123/testApp the link should be
http://123.123.123.123/testApp/Default.aspx
and If User open website from http://myservername.com/testApp the link should be
http://myservername.com/testApp/Default.aspx

Use REMOTE_ADDR server variable
string appPath = protocol +
System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] +
System.Web.HttpContext.Current.Request.ApplicationPath;

One of HTTP_HOST or SERVER_NAME should provide you with information on what user typed to get to your site. It may be good idea to check with Http debugger what browser actually sends in case of IP address to make sure you check correct values.
`HttpContext.Current.Request.ServerVariables("HTTP_HOST");`

Use this function to get the IPAddress of the user.
But there is a possibility that you may not get the actual IP. There are many concern like firewall etc. Which may expose same ip for all the computer on the network.
public static string GetMachineName(HttpRequest moRequest)
{
return moRequest.ServerVariables["HTTP_X_FORWARDED_FOR"] != null ||
moRequest.ServerVariables["HTTP_CLIENT_IP"] != null
? moRequest.ServerVariables["HTTP_X_FORWARDED_FOR"]
: moRequest.ServerVariables["REMOTE_ADDR"];
}

Related

Uniquely identify machine in web application using asp.net c#

I have one login page, user can use any machine while login into that page for the first time. once the user logged in for the first time, i need to restrict that user to not login into another machine. So user need to use only one machine that's used for the first time login.
I tried to get the client side mac address, but i can't able to get client side mac address in my website. Is there any other way to identity a machine uniquely?
For asp.net it's not possible to get the mac address of the client. You need to have some kind of windows application for that, that runs on the user's system.
A permanent cookie with a with a GUID might also be a solution.
Another solution might be to look up the servervariables when they make a request you will have Request.ServerVariables["REMOTE_ADDR"]; which would probably be the internal IP if the app is internal/intranet. There is also REMOTE_HOST. Sometimes these are filtered off by proxies/firewalls/nat but hopefully not in your situation.
Hope it helps!
if its intranet webapp, then you can enforce windows authentication - and keep a list of logged in users, in the database, with a timestamp of when the logged in user will automatically logout after the timestamp period.
Alternatively, use a cookie in forms authentication to do just that. But in any case, you will need the list of logged in users, and automatically log the user off, if he is on another machine.
More so, you can get the client's IP address and go from there, but its not reliable as it could be of an ISP. Its tricky, but cookies seems to be the simplest way of doing this.
However, a good solution would be to do it like IRC does, to keep track of logged in users. It sends a PING to the client, and expects the client to return a PONG, at different intervals of time. If the PONG is not received by the client, the IRC server automatically disconnects the user. Try this with something like SignalR. The downside of this is, if the user closes the browser and a PING request comes in, it will bounce back and the client will be disconnected as he/she will not be able to send a PONG request back.
I believe you want a user logged in on the website only in one session at any given time. Problem is that you can't know for sure when the user leaves, if he doesn't logout using the logout button.To fix this you have to have a timeout. I used a text file on the server in an application and it works.
Login button:
protected void btLogin_Click(object sender, EventArgs e)
{
if (check(txtPass.Text) && check(txtUser.Text))
{
var user = new UserManager().login(txtUser.Text, txtPass.Text);
if (user != null)
{
// this is the test you're looking for, the rest is only context
if (!FileManager.alreadyLoggedIn(user.email))
{
FormsAuthentication.SetAuthCookie(user.email, false);
}
else
{
//throw error that it is already connected in some other place
}
}
else
{
//throw error that login details are not OK
}
}
}
In a class two static methods:
//you have to call this function at every request a user makes
internal static void saveUserSessionID(string email)//email or any unique string to user
{
var dir = HostingEnvironment.MapPath("~/temp/UserSession/");// a folder you choose
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + email + ".txt";
File.WriteAllText(path, HttpContext.Current.Session.SessionID);
}
// if a request has not been made in tha last 4 minutes, the user left, closed the browser
// the test checks this only on a real server, localhost is not tested to be easy for the developer
internal static bool alreadyLoggedIn(string email)
{
var file = HostingEnvironment.MapPath("~/temp/UserSession/" + email + ".txt");
return File.Exists(file) && File.GetLastWriteTime(file).AddMinutes(4) > DateTime.Now && !HttpContext.Current.Request.IsLocal;
}
Obviously this is from another application, you can only take the idea and implement it in your own application. You can't just copy paste it.

How can i check if the web page is already accessed in particular IP Address on ASP.Net?

In my application i want to check that the url is accessed in the particular ip address. Only one time the page needs to be displayed and for the next time navigating to that page the page should not come.
How can i achieve this?
Regards,
Prasad
I've used this recently to identify users IP-Address(es) to log them on failed logins:
// Look for a proxy address first
var IP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
//Trim and lowercase IP if not null
if (IP != null)
{
IP = IP.ToLower().Trim();
}
if (IP == null || IP.Equals("unknown"))
{
//If IP is null use different detection method else pull the correct IP from list.
IP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToLower().Trim();
}
String[] IPs = null;
if (IP.IndexOf(",") > -1)
{
IPs = IP.Split(',');
}
else
{
IPs = new string[] { IP };
}
( note: converted from VB.NET )
Are you actually looking to display the page once per client, or genuinely once per IP?
If it's client machine based, then have that page store a cookie and check for it's presence to determine if the page has been visited before.
You can try storing the IP address in the database or you can make use of a cookie variable. Read more about Cookies
as suggested and described here: How to get a user's client IP address in ASP.NET?
you can check this in the Page_Load
Request.ServerVariables["REMOTE_ADDR"];
and if access was already done once you can use Server.Transfer to move to another page (like a warning page or back to home page etc...)
the way you persist which IP accessed your page once is up to you and your needs, Session, Application Cache, database, cookies...
When the page is loaded get the IP-address and store it in a database. Then, also when the page is loaded, check the IP against a possible entry in the database. If it doesn't exist, store it and load the page. If it aleady exists, redirect the user or something.

Unable to Get Ip address of the http request : Asp.Net [C#]

I have a page, on which a request from other website drops in. I want to track IP address where the request is coming.
I am using Asp.Net C# & used three methods
1) httpRequest.UserHostAddress
Tried Http Server variables as
2) httpRequest.ServerVariables ["HTTP_X_FORWARDED_FOR"];
3) httpRequest.ServerVariables ["REMOTE_ADDR"];
But these methods are returning me my server address. As browser is taking this request as it is origonated at my end. But i want to get ip address of the page (Site) where the request is coming from. Can anyone help me in this.
Maybe you're looking for the Url Referrer properties.
Try
Request.UrlReferrer
Or
Request.ServerVariables["http_referer"]
With this you get the Url where the request come from.
private IPAddress[] PossibleReferringIPs
{
get
{
Uri refer = Request.UrlReferrer;
if(refer == null)
return null;
string host = refer.Host;
IPAddress hostAsIP;
if(IPAddress.TryParse(host, out hostAsIP))// had actual IP address as host part of URI
return new IPAddress[]{hostAsIP};
return Dns.GetHostAddresses(host);//This can throw SocketException which you may wish to catch at this point.
}
}
We can't guarantee that the referrer is set at all, even if there was a referrer, and if there is more than one IP address assigned to the domain we cannot know which served the page as since there is no connection between that server and yours, that information isn't available.
Have you tried
httpRequest.UrlReferrer.Host
?

How to get the computer name (hostname in a web aplication)?

how can I get the client's computer name in a web application. The user in a network.
Regards
// Already tryed this option
string IP = System.Web.HttpContext.Current.Request.UserHostAddress;
string compName = DetermineCompName(IP);
System.Net.IPHostEntry teste = System.Net.Dns.GetHostEntry(IP);
ssresult = IP + " - " + teste.HostName;
// TODO: Write implementation for action
private static string DetermineCompName(string IP)
{
IPAddress myIP = IPAddress.Parse(IP);
IPHostEntry GetIPHost = Dns.GetHostEntry(myIP);
string[] compName = GetIPHost.HostName.ToString().Split('.');
return compName[0];
}
All of that, gives me only the IP :/
You can't do this in a way that is guaranteed to work.
The closest you will be able to get is to go down the route of doing a reverse dns lookup using System.Net.Dns.GetHostEntry which is what you have already tried.
The problem is that your machine has no way of knowing the hostname of a remote web client via its IP address alone (unless it is on the same subnet, in which case you may be able to retrieve it).
You have to fall back on your DNS infrastructure being able to map the IP back into a hostname [this is what nslookup does when you type in a hostname], and plenty of places just won't bother setting up reverse IP records.
Plus, often if they do, they won't match the hostname. It is quite common to see a reverse lookup for "1.2.3.4" come back as something line "machine-1.2.3.4", instead of the actual hostname.
This problem is exacerbated further if the clients are behind any sort of Network Address Translation so that many client computers have a single IP from an external perspective. This is probably not the case for you since you state "The user in a network".
As an aside, if you go to the server and type in, at a command prompt,
nslookup <some ip>
(where is an example of one of these client machines), do you get a hostname back?
If you do, then System.Net.Dns.GetHostEntry should be able to as well, if not then it probably can't for the reasons mentioned above.
you can get the windows machine name with - System.Environment.MachineName
Assuming your clients are Windows based running IE you could use this client side code to get the names and pass them back to the server:
<script type="text/javascript">
function create()
{
var net = new ActiveXObject("wscript.network");
document.write(net.ComputerName);
}
</script>
Yeah would require you to keep requesting and caching the computers terribly inefficient, was a bad idea.
I would go with running nslookup in the background I haven't tested this code and neither is it handling errors for failures, but basically, you can do:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo sInfo = new System.Diagnostics.ProcessStartInfo("nslookup.exe", "192.168.1.100");
string result = process.StandardOutput.ReadToEnd();
Then just parse the result value.

Getting ipaddress and location of every user visiting your website

How do you get the ipaddress and location of every website vistor of your website through Asp.Net?
Thanks
To get the user's IP use:
Request.UserHostAddress
You can use this webservice to get their geographic location.
http://iplocationtools.com/ip_location_api.php
string VisitorIPAddress = Request.UserHostAddress.ToString();
and based on the ipaddress you can narrow down the location: find the geographical location of a host
Request.UserHostAddress won’t work if you're behind a proxy. Use this code:
public static String GetIPAddress()
{
String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
else
ip = ip.Split(',')[0];
return ip;
}
Note that HTTP_X_FORWARDED_FOR should be used BUT as it can return multiple IP addresses separated by a comma you need to use the Split function. See this page for more info.
Well the following property should give you the IP Address of teh client (or the clients proxy server)
Request.UserHostAddress
As for location, you'd need to use some GeoIP/GeoLocation plugin like MaxMind to figure that out.
http://www.maxmind.com/
To get the IP do:
Request.UserHostAddress
And you can map IP to location using a webservice (slower) or a database (faster) like this:
http://ip-to-country.webhosting.info/node/view/5
It's server technology-agnostic, but I'd recommend piggy-backing on Google's AJAX loader: http://code.google.com/apis/ajax/documentation/#ClientLocation
It's in Javascript and will even give you the person's city/state/country (well, it takes a guess based on IP address). Post it back to the server and it's available to you in ASP.NET or whatever.

Categories

Resources