SoFunction
Updated on 2025-03-07

Example of C# programming method to obtain IP address

This article describes the method of C# programming to obtain IP addresses. Share it for your reference, as follows:

1. Obtain the client IP

/// <summary>
/// Get client Ip/// </summary>
/// <returns></returns>
public String GetClientIp()
{
  String clientIP = "";
  if ( != null)
  {
    clientIP = ["HTTP_X_FORWARDED_FOR"];
    if ((clientIP) || (() == "unknown"))
    {
      clientIP = ["HTTP_X_REAL_IP"];
      if ((clientIP))
      {
        clientIP = ["REMOTE_ADDR"];
      }
    }
    else
    {
      clientIP = (',')[0];
    }
  }
  return clientIP;
}

2. The server side obtains the client request IP and client machine name

/// <summary>
/// The server side obtains the client request IP and client machine name/// </summary>
public static void GetClientInfo()
{
  OperationContext context = ;
  MessageProperties messageProperties = ;
  RemoteEndpointMessageProperty endpointProperty = messageProperties[] as RemoteEndpointMessageProperty;
  HttpRequestMessageProperty requestProperty = messageProperties[] as HttpRequestMessageProperty;
  string clientIp = !(["X-Real-IP"]) ? ["X-Real-IP"] : ;
  string clientName = ;
  ("ClientIp: " + clientIp + "clientName:" + clientName);
}

PS: Here are a few IP-related tools for your reference:

Online query tool for IP address home location:
http://tools./aideddesign/ipcha

Online IP address/subnet mask calculation and conversion tools:
http://tools./aideddesign/ip_net_calc

Online Network Calculator | TCP/IP Subnet Mask Calculation and Conversion Tool:
http://tools./aideddesign/ipcalc

For more information about C# related content, please check out the topic of this site:Summary of thread usage techniques for C# programming》、《Summary of WinForm control usage》、《Summary of XML file operation skills in C#》、《Tutorial on the usage of common C# controls》、《C# data structure and algorithm tutorial》、《Summary of C# array operation skills"and"Introduction to C# object-oriented programming tutorial

I hope this article will be helpful to everyone's C# programming.