Example of C Programming Method for Getting IP Address
- 2021-12-04 10:54:50
- OfStack
In this paper, an example is given to describe the method of obtaining IP address by C # programming. Share it for your reference, as follows:
1. Get the client IP
/// <summary>
/// Get client Ip
/// </summary>
/// <returns></returns>
public String GetClientIp()
{
String clientIP = "";
if (System.Web.HttpContext.Current != null)
{
clientIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(clientIP) || (clientIP.ToLower() == "unknown"))
{
clientIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_REAL_IP"];
if (string.IsNullOrEmpty(clientIP))
{
clientIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
}
else
{
clientIP = clientIP.Split(',')[0];
}
}
return clientIP;
}
2. The server side obtains the client request IP and the client machine name
/// <summary>
/// The server side obtains the client request IP And client machine name
/// </summary>
public static void GetClientInfo()
{
OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
HttpRequestMessageProperty requestProperty = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
string clientIp = !string.IsNullOrEmpty(requestProperty.Headers["X-Real-IP"]) ? requestProperty.Headers["X-Real-IP"] : endpointProperty.Address;
string clientName = Environment.MachineName;
Console.WriteLine("ClientIp: " + clientIp + "clientName:" + clientName);
}
PS: Here we recommend several IP related tools for your reference:
IP address attribution online query tool:
http://tools.ofstack.com/aideddesign/ipcha
Online IP address/subnet mask calculation and conversion tool:
http://tools.ofstack.com/aideddesign/ip_net_calc
Online network calculator TCP/IP subnet mask calculation and conversion tool:
http://tools.ofstack.com/aideddesign/ipcalc
For more readers interested in C # related content, please check the topics on this site: "Summary of thread usage skills in C # programming", "Summary of WinForm control usage", "Summary of XML file operation skills in C #", "C # common control usage tutorial", "C # data structure and algorithm tutorial", "C # array operation skills summary" and "C # object-oriented programming introduction tutorial"
I hope this article is helpful to everyone's C # programming.