Подтвердить что ты не робот

Получить IP-адрес клиентской машины

Я пытаюсь получить IP-адрес клиентской машины с помощью С#. Я использую приведенный ниже код для получения IP-адреса:

string IPAddress = HttpContext.Current.Request.UserHostAddress;

Но он дает мне ответ в закодированном формате i.e fe80::ed13:dee2:127e:1264%13

Как я могу получить фактический IP-адрес? Любой, кто столкнулся с этой проблемой, поделитесь некоторыми идеями.

4b9b3361

Ответ 1

С#

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

Надеюсь, что это поможет

Ответ 2

попробуйте использовать

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

Ответ 3

В моем проекте требуется получить локальный IP-адрес ПК. Поэтому я использую его Пожалуйста, попробуйте приведенный ниже код

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

Ответ 4

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

Вы можете получить несколько IP-адресов, поэтому можете разделить их как -

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

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

        return Request.ServerVariables["REMOTE_ADDR"];
    }