Recording the IP address from Silverlight

Silverlight has no native way to get the client’s IP Address. Oh, sad clown of life, how you mock me. So, I had to go and do it myself. Why did I want to do such a thing? Because I was logging the IP Address of visitors to my site under certain conditions – (i.e., if they passed me bogus information, like a janky user ID field in the Silverlight control).

I handle errors from potentially malicious users by calling a web service. If the user ID variable is invalid, I call this web service like so:

      MyServiceClient WebService = new  MyServiceClient();
      WebService.ErrorHandlerCompleted += new EventHandler< MyLService.ErrorHandlingCompletedEventArgs>(ErrorLog_Completed);
      WebService.ErrorHandlingAsync("Invalid user ID sent",  "");

BTW, the ErrorLog_Completed method is empty – it’s just there because Silverlight requires it be there.

Which calls the web service in my web project:

        public bool ErrorHandling(string ErrorMessage, sstring IpAddress)
            Data.ErrorHandling(ErrorMessage,  IpAddress);
            return true;

The abbreviated error handling routing then takes, among other things, the IP Address sent from the Silverlight code. If the address sent is, then the Request.UserHostAddress method is called to get the honest-to-goodness IP Address. Remember to import the System.Web namespace.

public static bool ErrorHandling(string ErrorMessage, string IpAddress)
        if (IpAddress == "")
            IpAddress = HttpContext.Current.Request.UserHostAddress;
// Do database stuff here.

Not too tough, but a useful trick if you need the IP address. If you have a better way, please let me know  – I’m always interested in improving my code.

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: