My IP Address

My IP Detect the IP Address of your phone through an external service. In this tutorial we cover creating an MVC action to return your IP address, downloading a response from a web application and deserializing a JSON object.

Setup

Before jumping into the tutorials head to developer.windowsphone.com to download the free tools and get them installed.

Starting this application I thought it was going to be relatively quick one that I could knock togther in a few minutes. However it turns out there’s no way currently in Silverlight or Windows Phone 7 to determine the IP address of the client.

This means we’ll need to go out to an external service to get our IP Address, there are some issues this way in that depending on how your phone is connected to the internet could result in different addresses. We’ll go with a pretty simple method to detect the IP.

Since this site is based on ASP.NET MVC I added a new action to the solution with the following code, you can view the results at compiledexperience.com/windows-phone-7/my-ip. I highly reccomend using the Firefox addon JSON View to easily view the results. Update: This endpoint is no longer available.

[ActionName("My-IP")]
public JsonResult MyIP()
{
    return Json(new
    {
        ip = Request.UserHostAddress
    }, JsonRequestBehavior.AllowGet);
}

Again our UI is very simple, a couple of TextBlocks using the some of the built in Application Styles. The xaml is:

<Grid x:Name="ContentGrid" Grid.Row="1">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <TextBlock Text="your ip is:" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
    <TextBlock x:Name="IPAddress" Style="{StaticResource PhoneTextLargeStyle}" Text="127.0.0.1" Grid.Row="1">
        <TextBlock.Foreground>
            <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/>
        </TextBlock.Foreground>
    </TextBlock>
</Grid>

So our process is going to be:

  1. Download the json from the above link as a string.
  2. Deserialize the json into a .NET object.
  3. Populate the UI.

There a couple of different classes we can use to do http requests in WP7, the simplist is WebClient. One restriction (and in my opinion it’s a good one), is that all network communication in Silverlight and WP7 must be asynchronous. This means that we do the web request on a background thread, if we don’t then we could lock up the UI thread and hang the phone.

In the pages Loaded event we create the WebClient and attach a method to the OpenReadCompleted event, this occurs when the background web request has been completed. We then call OpenReadAsync with the uri of our MVC Action.

private void OnLoaded(object sender, RoutedEventArgs e)
{
    var webClient = new WebClient();

    webClient.OpenReadCompleted += OnOpenReadCompleted;

    webClient.OpenReadAsync(new Uri("http://compiledexperience.com/windows-phone-7/my-ip", UriKind.Absolute));
}

We’ll need a class to model the result we get back, it’s a pretty simple one with a single property. I’ve marked it up with DataContact and DataMember attributes, they’re not strictly nessecary if the JSON object mirrors our .NET object, but since I’m stickler for style we need to provide the name due to capitialisation differences between JSON and .NET.

[DataContract]
public class IPResult
{
    [DataMember(Name = "ip")]
    public string IP
    {
        get; set;
    }
}

When the web response comes back we’ll create a DataContractJsonSerializer for our IPResult class and deserialize an instance of it from the web response. From there it’s a simple matter of populating the UI.

private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    var serializer = new DataContractJsonSerializer(typeof(IPResult));
    var ipResult = (IPResult)serializer.ReadObject(e.Result);


    IPAddress.Text = ipResult.IP;
}

Download the Code

The code for all the tutorials is available to download: Windows Phone 7 Tutorials Solution.