
C# get ip address of client machine(3 methods)
There are usually three methods to get the client IP address in C#, the first one uses HTTP_X_FORWARDED_FOR, the second uses REMOTE_ADDR, the third uses UserHostAddress; all three methods use Request.
Sometimes, it may not be possible to get the IP in a certain way, so it is best to use the three methods at the same time, of course, you need to add if judgment. Next, introduce each method first, and then encapsulate the three methods into a callable method.
1. C# get ip with HTTP_X_FORWARDED_FOR
///<summary>
/// C# get ip address of client machine<
///</summary>
///<returns>IP address</returns>
public string GetClientIPAddr()
{
return Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
2. C# get ip with REMOTE_ADDR
///<summary>
///C# get ip address of client machine
///</summary>
///<returns>IP address</returns>
public string GetClientIPAddr()
{
return Request.ServerVariables["REMOTE_ADDR"];
}
3. C# get ip with UserHostAddress
///<summary>
///C# get ip address of client machine
///</summary>
///<returns>IP address</returns>
public string GetClientIPAddr()
{
return Request.UserHostAddress;
}
4. Three methods are used together to get IP(can be directly called)
///<summary>
///C# get ip address of client machine
///</summary>
///<returns>IP address</returns>
public string GetClientIPAddr()
{
string ipAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddr))
ipAddr = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(ipAddr))
ipAddr = HttpContext.Current.Request.UserHostAddress;
return ipAddr;
}
The above method of obtaining an IP address has passed the test in practical applications, they can accurately get the client IP address; if you want to use it, just use the fourth combination method.
-
Related Reading
- C# listview select row(a row and multiple rows)
- Javascript multidimensional array (create, add and r
- Javascript trim string whitespace, with removing lef
- C# convert punctuation marks to Unicode encoding
- C# Read and write to text file Newline, with one lin
- C# merge binary array(byte array)
- Excel Search function and SearchB usage(13 examples,
- Remove text after clicking in the textbox and then d
- C# Winform button transparent background with proper
- Convert Unicode to string C#(with string to unicode)
- C# set Winform icon and version number
- Javascript get referrer url(previous page url), curr