Sushri
Sushri

Reputation: 295

Get IP address of client machine

I am trying to get the IP address of client machine using C#. I am using the below code to get the IP address :

string IPAddress = HttpContext.Current.Request.UserHostAddress;

But it is giving me the response in encoded format i.e fe80::ed13:dee2:127e:1264%13

How can I get the actual IP address? Any one faced this issue please share some idea.

Upvotes: 17

Views: 81275

Answers (4)

Amarnath Balasubramanian
Amarnath Balasubramanian

Reputation: 9460

C#

string IPAddress = GetIPAddress();

public string GetIPAddress()
{
    IPHostEntry Host = default(IPHostEntry);
    string Hostname = null;
    Hostname = System.Environment.MachineName;
    Host = Dns.GetHostEntry(Hostname);
    foreach (IPAddress IP in Host.AddressList) {
        if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
            IPAddress = Convert.ToString(IP);
        }
    }
    return IPAddress;
}

VB.net

Dim Host As IPHostEntry
Dim Hostname As String
Hostname = My.Computer.Name
Host = Dns.GetHostEntry(Hostname)
For Each IP As IPAddress In Host.AddressList
    If IP.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
        IPAddress = Convert.ToString(IP)
    End If
    Next
Return IPAddress

Hope this helps

Upvotes: 16

Sapnandu
Sapnandu

Reputation: 642

In my project it's required to get the local PC IP. So i use it Please try the below code

string strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
string ip = addr[1].ToString();

Upvotes: 6

The Hungry Dictator
The Hungry Dictator

Reputation: 3484

try using this

string ip=System.Net.Dns.GetHostEntry
               (System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString();

Upvotes: 7

Ramashankar
Ramashankar

Reputation: 1658

private string GetUserIP()
 {
     return Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? Request.ServerVariables["REMOTE_ADDR"];    
 }

You may get several ip address, so can split them as-

private string GetUserIP()
    {
        string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (!string.IsNullOrEmpty(ipList))
        {
            return ipList.Split(',')[0];
        }

        return Request.ServerVariables["REMOTE_ADDR"];
    }

Upvotes: 10

Related Questions