X-Forwarded-For: How can I get the client's IP address in ASP.Net MVC? - c#

I'm totally new to the asp.net mvc stack and i was wondering what happened to the Request.Header object?
Basically what I want to do is to pull out the Device(PC) IP address, but I fail to retrieve the desired output. I also tried Request.ServerVariables object but result always remain NULL.
I am using asp.net MVC. is there any change in this function required:
public static string GetIP()
{
string functionReturnValue = null;
//Gets IP of actual device versus the proxy (WAP Gateway)
functionReturnValue = HttpContext.Current.Request.Headers["X-FORWARDED-FOR"]; //functionReturnValue = null
if (string.IsNullOrEmpty(functionReturnValue))
{
functionReturnValue = HttpContext.Current.Request.Headers["X-Forwarded-For"];//functionReturnValue = null
if (string.IsNullOrEmpty(functionReturnValue))
{
//If not using a proxy then get the device IP
// GetIP = Context.Request.ServerVariables("REMOTE_ADDR")
if (string.IsNullOrEmpty(functionReturnValue))
{
//If not using a proxy then get the device IP
functionReturnValue = HttpContext.Current.Request.Headers["X-CLIENT-IP"];//functionReturnValue = null
if (string.IsNullOrEmpty(functionReturnValue))
{
//If not using a proxy then get the device IP
functionReturnValue = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];//functionReturnValue = "::1"
}
}
}
}
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("(\\d{1,3}\\.){3}\\d{0,3}");
if (functionReturnValue != null)
{
if (regex.IsMatch(functionReturnValue))
{
functionReturnValue = regex.Match(functionReturnValue).Value.ToString();
}
else
{
functionReturnValue = "";
}
regex = null;
}
if (functionReturnValue == null)
{
return "";
}
else
{
return functionReturnValue;
}
}

In X-Forwarded-For you will get client ip,proxy1 & proxy2. By taking first item you will get client/user ip.
HttpContext.Current.Request.Headers["X-Forwarded-For"].Split(new char[] { ',' }).FirstOrDefault()
Hope it helps!

Related

Error Getting Address from GetAddress - Trezor Development

I'm building a C# HID library for the Trezor. It's working well. I'm able to get past the pin entry and retrieve my xpub, and I can get addresses. However, none of the addresses that are getting returned match any of my addresses in the Trezor wallet website.
You can see the HID doco here:
https://doc.satoshilabs.com/trezor-tech/api-workflows.html#passphrase-meta-workflow
This is not really a C# question. Rather, it's a general question for any Trezor HID developers. The big problem is that if I pass a HDNodePathType message as the Multisig property of the GetAddress method, I get the error "Can't encode address'". What do I need to pass with the GetAddress message to get a valid address?
Here is an Android repo:
https://github.com/trezor/trezor-android
This problem has now been resolved. Trezor.Net has a working example can be cloned here.
Here is the code for getting an address:
public async Task<string> GetAddressAsync(IAddressPath addressPath, bool isPublicKey, bool display, AddressType addressType, InputScriptType inputScriptType, string coinName)
{
try
{
var path = addressPath.ToArray();
if (isPublicKey)
{
var publicKey = await SendMessageAsync<PublicKey, GetPublicKey>(new GetPublicKey { CoinName = coinName, AddressNs = path, ShowDisplay = display, ScriptType = inputScriptType });
return publicKey.Xpub;
}
else
{
switch (addressType)
{
case AddressType.Bitcoin:
//Ultra hack to deal with a coin name change in Firmware Version 1.6.2
if ((Features.MajorVersion <= 1 && Features.MinorVersion < 6) && coinName == "Bgold")
{
coinName = "Bitcoin Gold";
}
return (await SendMessageAsync<Address, GetAddress>(new GetAddress { ShowDisplay = display, AddressNs = path, CoinName = coinName, ScriptType = inputScriptType })).address;
case AddressType.Ethereum:
var ethereumAddress = await SendMessageAsync<EthereumAddress, EthereumGetAddress>(new EthereumGetAddress { ShowDisplay = display, AddressNs = path });
var sb = new StringBuilder();
foreach (var b in ethereumAddress.Address)
{
sb.Append(b.ToString("X2").ToLower());
}
var hexString = sb.ToString();
return $"0x{hexString}";
default:
throw new NotImplementedException();
}
}
}
catch (Exception ex)
{
Logger?.Log("Error Getting Trezor Address", LogSection, ex, LogLevel.Error);
throw;
}
}

How do I find the local IP address on a Win 10 UWP project

I am currently trying to port an administrative console application over to a Win 10 UWP app. I am having trouble with using the System.Net.Dns from the following console code.
How can I get the devices IP
Here is the console app code that I am trying to port over.
public static string GetIP4Address()
{
string IP4Address = String.Empty;
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily == AddressFamily.InterNetwork)
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
Use this to get host IPaddress in a UWP app, I've tested it:
foreach (HostName localHostName in NetworkInformation.GetHostNames())
{
if (localHostName.IPInformation != null)
{
if (localHostName.Type == HostNameType.Ipv4)
{
textblock.Text = localHostName.ToString();
break;
}
}
}
And see the API Doc here
You may try like this :
private string GetLocalIp()
{
var icp = NetworkInformation.GetInternetConnectionProfile();
if (icp?.NetworkAdapter == null) return null;
var hostname =
NetworkInformation.GetHostNames()
.SingleOrDefault(
hn =>
hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId
== icp.NetworkAdapter.NetworkAdapterId);
// the ip address
return hostname?.CanonicalName;
}
the answer above is also right
based on answer by #John Zhang, but with fix to not throw LINQ error about multiple matches and return Ipv4 address:
public static string GetFirstLocalIp(HostNameType hostNameType = HostNameType.Ipv4)
{
var icp = NetworkInformation.GetInternetConnectionProfile();
if (icp?.NetworkAdapter == null) return null;
var hostname =
NetworkInformation.GetHostNames()
.FirstOrDefault(
hn =>
hn.Type == hostNameType &&
hn.IPInformation?.NetworkAdapter != null &&
hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId);
// the ip address
return hostname?.CanonicalName;
}
obviously you can pass HostNameType.Ipv6 instead of the Ipv4 which is the default (implicit) parameter value to get the Ipv6 address

How to get the public IP address of a user in C#

I want the public IP address of the client who is using my website.
The code below is showing the local IP in the LAN, but I want the public IP of the client.
//get mac address
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty)// only return MAC Address from first card
{
IPInterfaceProperties properties = adapter.GetIPProperties();
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
}
// To Get IP Address
string IPHost = Dns.GetHostName();
string IP = Dns.GetHostByName(IPHost).AddressList[0].ToString();
Output:
Ip Address : 192.168.1.7
Please help me to get the public IP address.
This is what I use:
protected void GetUser_IP()
{
string VisitorsIPAddr = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}
uip.Text = "Your IP is: " + VisitorsIPAddr;
}
"uip" is the name of the label in the aspx page that shows the user IP.
You can use "HTTP_X_FORWARDED_FOR" or "REMOTE_ADDR" header attribute.
Refer method GetVisitorIPAddress from Machine Syntax blog .
/// <summary>
/// method to get Client ip address
/// </summary>
/// <param name="GetLan"> set to true if want to get local(LAN) Connected ip address</param>
/// <returns></returns>
public static string GetVisitorIPAddress(bool GetLan = false)
{
string visitorIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = HttpContext.Current.Request.UserHostAddress;
if (string.IsNullOrEmpty(visitorIPAddress) || visitorIPAddress.Trim() == "::1")
{
GetLan = true;
visitorIPAddress = string.Empty;
}
if (GetLan && string.IsNullOrEmpty(visitorIPAddress))
{
//This is for Local(LAN) Connected ID Address
string stringHostName = Dns.GetHostName();
//Get Ip Host Entry
IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
//Get Ip Address From The Ip Host Entry Address List
IPAddress[] arrIpAddress = ipHostEntries.AddressList;
try
{
visitorIPAddress = arrIpAddress[arrIpAddress.Length - 2].ToString();
}
catch
{
try
{
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
try
{
arrIpAddress = Dns.GetHostAddresses(stringHostName);
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
visitorIPAddress = "127.0.0.1";
}
}
}
}
return visitorIPAddress;
}
Combination of all of these suggestions, and the reasons behind them. Feel free to add more test cases too. If getting the client IP is of utmost importance, than you might wan to get all of theses are run some comparisons on which result might be more accurate.
Simple check of all suggestions in this thread plus some of my own code...
using System.IO;
using System.Net;
public string GetUserIP()
{
string strIP = String.Empty;
HttpRequest httpReq = HttpContext.Current.Request;
//test for non-standard proxy server designations of client's IP
if (httpReq.ServerVariables["HTTP_CLIENT_IP"] != null)
{
strIP = httpReq.ServerVariables["HTTP_CLIENT_IP"].ToString();
}
else if (httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
strIP = httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
//test for host address reported by the server
else if
(
//if exists
(httpReq.UserHostAddress.Length != 0)
&&
//and if not localhost IPV6 or localhost name
((httpReq.UserHostAddress != "::1") || (httpReq.UserHostAddress != "localhost"))
)
{
strIP = httpReq.UserHostAddress;
}
//finally, if all else fails, get the IP from a web scrape of another server
else
{
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
strIP = sr.ReadToEnd();
}
//scrape ip from the html
int i1 = strIP.IndexOf("Address: ") + 9;
int i2 = strIP.LastIndexOf("</body>");
strIP = strIP.Substring(i1, i2 - i1);
}
return strIP;
}
That code gets you the IP address of your server not the address of the client who is accessing your website. Use the HttpContext.Current.Request.UserHostAddress property to the client's IP address.
For Web Applications ( ASP.NET MVC and WebForm )
/// <summary>
/// Get current user ip address.
/// </summary>
/// <returns>The IP Address</returns>
public static string GetUserIPAddress()
{
var context = System.Web.HttpContext.Current;
string ip = String.Empty;
if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
ip = context.Request.UserHostAddress;
if (ip == "::1")
ip = "127.0.0.1";
return ip;
}
For Windows Applications ( Windows Form, Console, Windows Service , ... )
static void Main(string[] args)
{
HTTPGet req = new HTTPGet();
req.Request("http://checkip.dyndns.org");
string[] a = req.ResponseBody.Split(':');
string a2 = a[1].Substring(1);
string[] a3=a2.Split('<');
string a4 = a3[0];
Console.WriteLine(a4);
Console.ReadLine();
}
So many of these code snippets are really big and could confuse new programmers looking for help.
How about this simple and compact code to fetch the IP address of the visitor?
string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
Simple, short and compact.
I have an extension method:
public static string GetIp(this HttpContextBase context)
{
if (context == null || context.Request == null)
return string.Empty;
return context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
?? context.Request.UserHostAddress;
}
Note: "HTTP_X_FORWARDED_FOR" is for ip behind proxy. context.Request.UserHostAddress is identical to "REMOTE_ADDR".
But bear in mind it is not necessary the actual IP though.
Sources:
IIS Server Variables
Link
My version handles both ASP.NET or LAN IPs:
/**
* Get visitor's ip address.
*/
public static string GetVisitorIp() {
string ip = null;
if (HttpContext.Current != null) { // ASP.NET
ip = string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"])
? HttpContext.Current.Request.UserHostAddress
: HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
if (string.IsNullOrEmpty(ip) || ip.Trim() == "::1") { // still can't decide or is LAN
var lan = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(r => r.AddressFamily == AddressFamily.InterNetwork);
ip = lan == null ? string.Empty : lan.ToString();
}
return ip;
}
private string GetClientIpaddress()
{
string ipAddress = string.Empty;
ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipAddress == "" || ipAddress == null)
{
ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
return ipAddress;
}
else
{
return ipAddress;
}
}
On MVC 5 you can use this:
string cIpAddress = Request.UserHostAddress; //Gets the client ip address
or
string cIpAddress = Request.ServerVariables["REMOTE_ADDR"]; //Gets the client ip address
In MVC IP can be obtained by the following Code
string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;
just use this..................
public string GetIP()
{
string externalIP = "";
externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
return externalIP;
}
We connect to servers that give us our external IP address and try to parse the IP from returning HTML pages. But when servers make small changes on these pages or remove them, these methods stop working properly.
Here is a method that takes the external IP address using a server which has been alive for years and returns a simple response rapidly...
https://www.codeproject.com/Tips/452024/Getting-the-External-IP-Address
Private string getExternalIp()
{
try
{
string externalIP;
externalIP = (new
WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
return externalIP;
}
catch { return null; }
}
VB.NET
Imports System.Net
Private Function GetExternalIp() As String
Try
Dim ExternalIP As String
ExternalIP = (New WebClient()).DownloadString("http://checkip.dyndns.org/")
ExternalIP = (New Regex("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")) _
.Matches(ExternalIP)(0).ToString()
Return ExternalIP
Catch
Return Nothing
End Try
End Function
lblmessage.Text =Request.ServerVariables["REMOTE_HOST"].ToString();
You can download xNet at: https://drive.google.com/open?id=1fmUosINo8hnDWY6s4IV4rDnHKLizX-Hq
First, you need import xNet, code:
using xNet;
Code:
void LoadpublicIP()
{
HttpRequest httprequest = new HttpRequest();
String HTML5 = httprequest.Get("https://whoer.net/").ToString();
MatchCollection collect = Regex.Matches(HTML5, #"<strong data-clipboard-target="".your-ip(.*?)</strong>", RegexOptions.Singleline);
foreach (Match match in collect)
{
var val = Regex.Matches(match.Value, #"(?<ip>(\d|\.)+)");
foreach (Match m in val)
{
richTextBox1.Text = m.Groups[2].Value;
}
}
}

How to get machine account from which the user login to my application?

How to get the user machine account from which he access the application in the case of Form authentication .
I use the following method but it doesn't get the required data:
protected string[] TrackUser()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string IP = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
string compName = (Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName);
string account = Request.ServerVariables["AUTH_USER"];
string[] user_network_data = new string[3];
if (!string.IsNullOrEmpty(IP))
{
string[] addresses = IP.Split(',');
if (addresses.Length != 0)
{
IP = addresses[0];
}
}
else
{
IP = context.Request.ServerVariables["REMOTE_ADDR"];
}
user_network_data[0] = IP;
user_network_data[1] = compName;
user_network_data[2] = account;
return user_network_data;
}
I think you're just grabbing the wrong initial information from the request. Try these:
string IP = context.Request.UserHostAddress;
string compName = context.Request.UserHostName;
string account = context.Request.LogonUserIdentity.Name;
I think the rest of your code should work fine once you have the right data to start off with.

Outlook : How to get email from Recipient field?

I'm attempting to get the email address typed into the To field of a compose mail window.
I try to get the Address property of a Recipient, which according to VS, should give me the email.
I am instead receiving a string that looks like this:
"/c=US/a=att/p=Microsoft/o=Finance/ou=Purchasing/s=Furthur/g=Joe"
How can I get the email address in the recipient field?
My code so far:
List <string> emails = new List<string>();
if (thisMailItem.Recipients.Count > 0)
{
foreach (Recipient rec in thisMailItem.Recipients)
{
emails.Add(rec.Address);
}
}
return emails;
Can you try this ?
emails.Add(rec.AddressEntry.Address);
Reference link
EDIT:
I don't have the right environment to test so I'm just guessing all this, but how about
string email1Address = rec.AddressEntry.GetContact().Email1Address;
or .Email2Adress or .Email3Address
Also there is,
rec.AddressEntry.GetExchangeUser().Address
that you might want to try.
Try this
private string GetSMTPAddressForRecipients(Recipient recip)
{
const string PR_SMTP_ADDRESS =
"http://schemas.microsoft.com/mapi/proptag/0x39FE001E";
PropertyAccessor pa = recip.PropertyAccessor;
string smtpAddress = pa.GetProperty(PR_SMTP_ADDRESS).ToString();
return smtpAddress;
}
This is available on MSDN here
I have used the same way to get email addresses in my application and its working.
the AddressEntry also has an SMTPAddress property that exposes the primary smtp adress of the user.
I don't know if this helps or how accurate
it is, a sample
private string GetSmtp(Outlook.MailItem item)
{
try
{
if (item == null || item.Recipients == null || item.Recipients[1] == null) return "";
var outlook = new Outlook.Application();
var session = outlook.GetNamespace("MAPI");
session.Logon("", "", false, false);
var entryId = item.Recipients[1].EntryID;
string address = session.GetAddressEntryFromID(entryId).GetExchangeUser().PrimarySmtpAddress;
if (string.IsNullOrEmpty(address))
{
var rec = item.Recipients[1];
var contact = rec.AddressEntry.GetExchangeUser();
if (contact != null)
address = contact.PrimarySmtpAddress;
}
if (string.IsNullOrEmpty(address))
{
var rec = item.Recipients[1];
var contact = rec.AddressEntry.GetContact();
if (contact != null)
address = contact.Email1Address;
}
return address;
}
finally
{
}
}

Categories

Resources