Thursday, August 4, 2016

Get IP Address in Web and Windows Application in .NET

Web Applications and websites are deployed in a server and in order to get 
IP Address of the client PC from where client accesses the website through
browser, C# code is as follows :

string ipaddress;
ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipaddress == "" || ipaddress == null)
        ipaddress = Request.ServerVariables["REMOTE_ADDR"];

Output will be end user's public IP.

Please note if the user runs the Application from local PC, output will be
the localhost address which is 127.0.0.1

Get IP Address from a Windows Application:

Scenario:
In the example below I will explain how to get IP Address on a button click.

Since it has to access Network and socket information, we have to add the
following namespaces:

using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;

private void button1_Click(object sender, EventArgs e)
{
     string str = getIP();
}

string getIP()
{
       string ipAddress = "";
       var ni = NetworkInterface.GetAllNetworkInterfaces();

       foreach (NetworkInterface item in ni)
       {
              int c = item.GetIPProperties().GatewayAddresses.Count;
              if (item.GetIPProperties().GatewayAddresses.Count > 0)
              {
                    var addr = item.GetIPProperties().GatewayAddresses[0].Address;
                    if (addr != null)
                    {
                        if (!addr.ToString().Equals("0.0.0.0"))
                        {
                            if ((item.OperationalStatus == OperationalStatus.Up) && (item.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || item.NetworkInterfaceType == NetworkInterfaceType.Ethernet))
                            {
                                foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
                                {
                                    if (ip.Address.AddressFamily == AddressFamily.InterNetwork & !IPAddress.IsLoopback(ip.Address))
                                    {
                                        ipAddress = ip.Address.ToString();

                                    }
                                }
                            }
                        }
                    }
                }
            }
            return ipAddress;
  }

The function above is to get the exact IP Address as a system might have multiple Network Interfaces.


No comments:

Post a Comment