How to get client ip address in MVC - c#

I would like to pull out the client's PC's IP address. I have tried below approaches but it always returns "::1"
1. var test = this.Request.ServerVariables.Get("REMOTE_ADDR");
2. request.UserHostAddress;
Any inputs?

You can get the I.P address like this in your Controller method:
If the client machine is behind a proxy server, we can check for the variable HTTP_X_FORWARDED_FOR:
string ip;
ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
If the IP Address is not found in the HTTP_X_FORWARDED_FOR server variable, it means that it is not using any Proxy Server and hence the IP Address is now checked in the REMOTE_ADDR server variable.
Note: On your local machine, the I.P address will be shown as ::1 which is an IPV6 loopback address (i.e. localhost). An IPV4 address would be 127.0.0.1.
This is because in such case the Client and Server both are the same machine. When the application is deployed on the server, then the result will be different.

The below code should give you collection of client IP Addresses. If not, please post your code snippet so we can verify:
public static System.Collections.Generic.IReadOnlyCollection<System.Net.IPAddress> GetIpAddresses()
{
var ipAddresses = new List<System.Net.IPAddress>();
foreach (var values in GetValues(System.Web.HttpContext.Current.Request.Headers, "X-Forwarded-For"))
{
foreach (var ipv in values.Split(new char[] { ',', ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
if (ipv.Contains(":"))
{
var array = ipv.Split(':');
ipAddresses.Add(array.Length == 2 ? System.Net.IPAddress.Parse(array[0].Trim()) : System.Net.IPAddress.Parse(ipv.Trim()));
}
else
{
ipAddresses.Add(System.Net.IPAddress.Parse(ipv));
}
}
}
if (request.UserHostAddress != null)
{
if (request.UserHostAddress.Contains(":"))
{
var array = request.UserHostAddress.Split(':');
ipAddresses.Add(array.Length == 2 ? System.Net.IPAddress.Parse(array[0].Trim()) : System.Net.IPAddress.Parse(request.UserHostAddress.Trim()));
}
else
{
ipAddresses.Add(System.Net.IPAddress.Parse(request.UserHostAddress));
}
}
return ipAddresses;
}

Related

How to get client ipaddress and device name who logs in to my website using c#

I have searched and read almost every article related to my search about how to get client ipaddress and machine name but all the codes return only server ip and name. I've tried these codes also given below, it gives my PC ip on localhost but on the server, it gives server ip and name :
string stringHostName = Dns.GetHostName();
IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
and also used this method :
public string GetUserIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDER_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}enter code here
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
It gives ::1 on localhost but on the server it gives server ip only.
Kindly help me if there any way possible to get client ipaddress and machine name using C#.

Send E-mail notification If a certain value (IP Address) is found in the array

I have a C# console application and want to be able to send an Email to a certain address if any IP addresses that are not local are found in the array, I am assuming I would use a If != statement but i cannot get anything to work. Any tips or help would be greatly appreciated.
System.Net.IPAddress[] addresslist = Dns.GetHostAddresses(C);
{
string IPs = "";
bool firstIP = true;
foreach (IPAddress ip in addresslist)
{
if (!firstIP)
{
IPs = IPs + ",";
}
IPs = IPs + ip;
firstIP = false;
}
addresslist.ToString();
if addresslist != { "10.1.20.99"} //example, have multiple IP's
then //..... this is where I am stuck
you can remove local addresses with
var filteredIPs = ipaddresslist.Where(p => !p.StartsWith("10.1"));
Then you can send a message with something like sendimportantmails(String.Join(",", filteredIPs));

Why my code doesn't pick correct IP address ? [duplicate]

I am running an ASP.NET MVC app in the localhost - dev server given with a Visual Studio. I want to get the IP address. I tried
Request.UserHostAddress
and
Request.ServerVariables("REMOTE_ADDR")
In both cases, I am getting::1 as a result. What is it? Why am I getting it? How can I get 127.0.0.1 or 192.168.1.xxx?
You are getting a valid IP Address; ::1 is localhost for IPv6.
What you're seeing when calling 'localhost' is valid. ::1 is the IPv6 loopback address. Equivalent to 127.0.0.1 for IPv4.
Instead of calling:
http://localhost/...
Call:
http://{machinename}/...
or
http://127.0.0.1/...
or
http://192.168.1.XXX/...
[Replace {machinename} with your machine's computer name. Replace XXX with your computer's IP address.]
Anyone calling into your machine to the MVC app will have their valid IP address as a result. If the client is an IPv6 host it will save their IPv6 IP address. If the client is an IPv4 host it will save their IPv4 IP address.
If you always want to save an IPv4 address take a look at this article on how they accomplished it with a simple class https://web.archive.org/web/20211020102847/https://www.4guysfromrolla.com/articles/071807-1.aspx. You should be able to take their example and build a quick helper method to accomplish this.
Request.Params["REMOTE_ADDR"]
instead of Request.ServerVariables("REMOTE_ADDR")
If you want localhost return 127.0.0.1, maybe you need to change your "hosts" file.
You can find it in "%systemdrive%\Windows\System32\drivers\etc"
It works for me, now I get 127.0.0.1 with "Request.ServerVariables["REMOTE_ADDR"]". I uncomment 127.0.0.1 (remove #).
Here you can find default hosts file
http://support.microsoft.com/kb/972034
My file
# localhost name resolution is handled within DNS itself.
127.0.0.1 localhost
# ::1 localhost
below code i have used for finding ip
public static string GetIp()
{
var Request = HttpContext.Current.Request;
try
{
Console.WriteLine(string.Join("|", new List<object> {
Request.UserHostAddress,
Request.Headers["X-Forwarded-For"],
Request.Headers["REMOTE_ADDR"]
})
);
var ip = Request.UserHostAddress;
if (Request.Headers["X-Forwarded-For"] != null)
{
ip = Request.Headers["X-Forwarded-For"];
Console.WriteLine(ip + "|X-Forwarded-For");
}
else if (Request.Headers["REMOTE_ADDR"] != null)
{
ip = Request.Headers["REMOTE_ADDR"];
Console.WriteLine(ip + "|REMOTE_ADDR");
}
return ip;
}
catch (Exception ex)
{
Log.WriteInfo("Message :" + ex.Message + "<br/>" + Environment.NewLine +
"StackTrace :" + ex.StackTrace);
}
return null;
}
If you get ipv6 address , after that you can find it valid ipv4 address map for ipv6 address.
c # code is below;
public static string GetIP4Address(string ip) {
try {
var hostNames = Dns.GetHostEntry(ip);
var ipv4 = hostNames.AddressList.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
if(ipv4 != null) {
return ipv4.ToString();
}
} catch(Exception ex) {
log.WarnFormat("Error When Getting Client Ipv4");
}
return ip;
}

How to detect static ip using win app in c#

Please correct me if i am wrong. There are two types of IP -
One, the static(fixed) IP address we assign to the LAN card and second that we received from the service provider.
For ex. The IP address set for my machine is 192.168.1.10 while the IP address given by ISP is 218.64.xx.xx. (You can check this using http://www.ip2location.com/)
When I use ASP.net, i can get the IP address provided by ISP using -
HttpContext.Current.Request.UserHostAddress;
The Problem:
Now, I am working in Windows Forms environment but unable to get the IP provided by ISP, though I am able to get the fixed IP.
Can anybody help me?
Thanks for sharing your time.
You're trying to get the external IP address of your router.
You need to send an HTTP request to a third-party service which will reply with the IP address.
You can do that using the WebClient class.
For example:
///<summary>Gets the computer's external IP address from the internet.</summary>
static IPAddress GetExternalAddress() {
//<html><head><title>Current IP Check</title></head><body>Current IP Address: 129.98.193.226</body></html>
var html = new WebClient().DownloadString("http://checkip.dyndns.com/");
var ipStart = html.IndexOf(": ", StringComparison.OrdinalIgnoreCase) + 2;
return IPAddress.Parse(html.Substring(ipStart, html.IndexOf("</", ipStart, StringComparison.OrdinalIgnoreCase) - ipStart));
}
The terminology is wrong; your machine has a private IP and a public IP (not "static" and "dynamic").
To get the public IP, you need to bounce off a public server, e.g., whatismyip.org or your own server.
i found manu methods one of them is a html request to http://whatismyip.com
public static IPAddress GetExternalIp()
{
string whatIsMyIp = "http://whatismyip.com";
string getIpRegex = #"(?<=<TITLE>.*)\d*\.\d*\.\d*\.\d*(?=</TITLE>)";
WebClient wc = new WebClient();
UTF8Encoding utf8 = new UTF8Encoding();
string requestHtml = "";
try
{
requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
}
catch (WebException we)
{
// do something with exception
Console.Write(we.ToString());
}
Regex r = new Regex(getIpRegex);
Match m = r.Match(requestHtml);
IPAddress externalIp = null;
if (m.Success)
{
externalIp = IPAddress.Parse(m.Value);
}
return externalIp;
}
or use
IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName());
Console.Write(IPHost.AddressList[0].ToString());
you can try this in the System.Net namespace:
Dns.GetHostAddresses(Dns.GetHostName())
try with this (using System.Net):
IPHostEntry he = Dns.GetHostByName(Dns.GetHostName());
var s = he.AddressList[0].ToString(); // returns IP address

How to get the server IP Address (in C# / asp.net)?

Is there a 1 line method to get the IP Address of the server?
Thanks
Request.ServerVariables["LOCAL_ADDR"];
From the docs:
Returns the server address on which the request came in. This is important on computers where there can be multiple IP addresses bound to the computer, and you want to find out which address the request used.
This is distinct from the Remote addresses which relate to the client machine.
From searching the net I found following code: (I couldn't find a single line method there)
string myHost = System.Net.Dns.GetHostName();
// Show the hostname
MessageBox.Show(myHost);
// Get the IP from the host name
string myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[index].ToString();
// Show the IP
MessageBox.Show(myIP);
-> where index is the index of your ip address host (ie. network connection).
Code from: http://www.geekpedia.com/tutorial149_Get-the-IP-address-in-a-Windows-application.html
As other(s) have posted, System.Net.Dns.GetHostEntry is the way to go. When you access the AddressList property, you'll want to take the AddressFamily property into account, as it could return both IPv4 AND IPv6 results.
This method will return your machine public IP address when run this code on your PC and when you deploy your application on server will return Server IP address.
public static string Getpublicip()
{
try
{
string externalIP = "";
var request = (HttpWebRequest)WebRequest.Create("http://icanhazip.com.ipaddress.com/");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
externalIP = new WebClient().DownloadString("http://icanhazip.com");
return externalIP;
}
catch (Exception e)
{
return "null";
}
}

Categories