Unable to Get the client machine and IP address from C#

0

I am using the below mention code get the client machine name and IP. But it is not working. Help me out fix this issue. I am getting the following error System.Net.Sockets.SocketException (0x80004005): No such host is known at System.Net.Dns.InternalGetHostByAddress(IPAddress address, Boolean includeIPv6) at System.Net.Dns.GetHostEntry(IPAddress address)

    static string GetIP()
    {
        try
        {
            if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request["HTTP_CF_CONNECTING_IP"]))
            {
                return System.Web.HttpContext.Current.Request["HTTP_CF_CONNECTING_IP"].ToString();
            }
            else if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request["HTTP_X_FORWARDED_FOR"]))
            {
                return System.Web.HttpContext.Current.Request["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request["REMOTE_HOST"]))
            {
                return System.Web.HttpContext.Current.Request["REMOTE_HOST"].ToString();
            }
            else
            {
                return System.Web.HttpContext.Current.Request["REMOTE_ADDR"].ToString();
            }
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }

    }


    public static string GetClientMachineName()
    {
        StringBuilder strClientName = new StringBuilder("");

        try
        {
            string IP = GetIP();
            IPAddress myIP = IPAddress.Parse(IP);
            strClientName.Append(IP);
            strClientName.Append(" " + "@@" + " ");
            if (System.Web.HttpContext.Current.Request["HTTP_VIA"] != string.Empty)
            {
                strClientName.Append(System.Web.HttpContext.Current.Request["HTTP_VIA"]);
                strClientName.Append(",");
            }
            strClientName.Append("myIP." +myIP.ToString());

            IPHostEntry GetIPHost = Dns.GetHostEntry(myIP);
            strClientName.Append(GetIPHost.HostName.ToString());
            strClientName.Append(" " + "@@" + " ");
            for (int i = 0; i <= GetIPHost.AddressList.Length - 1; i++)
            {
                strClientName.Append(GetIPHost.AddressList[i].ToString());
                strClientName.Append(" " + "@@" + " ");
            }

            return strClientName.ToString();
        }
        catch (Exception ex)
        {
            return strClientName.ToString() + "-----------" + ex.ToString();
        }

    }
model-view-controller
asked on Stack Overflow May 10, 2019 by Zawar Ahmad • edited May 10, 2019 by Zawar Ahmad

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0