views:

854

answers:

1

I am using ASP.Net (.asmx) web services with Silverlight. since there is no way to find client ip address in Silverlight, therefore I had to log this on service end. these are some methods I have tried:

Request.ServerVariables(”REMOTE_HOST”)
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
Request.UserHostAddress()
Request.UserHostName()
string strHostName = System.Net.Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();

All the above methods work fine on my local system, but when I publish my service on production server. it starts giving errors.

Error: Object reference not set to an instance of an object. StackTrace: at System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32 index) at System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String name) at System.Web.Hosting.ISAPIWorkerRequest.GetRemoteAddress() at System.Web.HttpRequest.get_UserHostAddress()

+1  A: 

You should try to find out exactly where the NullReferenceException is coming from. Change your code to understand that certain things can return null. For instance, in

HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]

HttpContext.Current could retrun null, or .Request could return null, or .ServerVariables["REMOTE_ADDR"] could return null. Also, in

string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();

the GetHostAddresses(strHostName) could return null, or the .GetValue(0) could return null.

If a method or property could return null, then you should check for null before dereferencing it. For instance,

IPAddress[] hostAddresses = System.Net.Dns.GetHostAddresses(strHostName);
string clientIPAddress;
if (hostAddresses != null)
{
    object value = hostAddresses.GetValue(0);
    if (value != null)
    {
        clientIPAddress = value.ToString();
    }
}

P.S. I don't know why you'd use GetValue(0). Use hostAddresses[0] instead.

John Saunders
NULL Reference Exception occurs when I try Request.UserHostAddress or HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]I just cant find out any way to get the client IP in my asmx service. =(
Zain Shaikh
@Zain: Like I said, check for null before you use any of these values. In fact, make sure to test `HttpContext.Current` to see if it's null before you try `HttpContext.Current.Request`.
John Saunders