Reputation: 7830
I have hosted Web Api developed in ASP.net. I want if someone call my API so I can log in database so later on if I want to reject request from particular id using C#.
What is best practice to get consumer IP and HostName?
public static string GetIP4Address()
{
string IP4Address = String.Empty;
foreach (IPAddress IPA in Dns.GetHostAddresses(Request.ServerVariables["REMOTE_ADDR"].ToString())))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != String.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
Upvotes: 2
Views: 23543
Reputation: 48230
Resolving names sounds like a bad idea. What if you are called from a client machine that dns doesn't resolve? I tell you, dns takes forever and then fails with an exception you have to catch and log as "unknown host name".
As for request address, just get it with
HttpContext.Current.Request.UserHostAddress
Upvotes: 8