Let us see the procedure for programmatically getting the IP address in Windows Phone 8. Create a new project with a valid name. Once everything is ready our project will look as in the following screen.
![page name]()
Now add one Button control to the triggers and show the IP address, change the button name to “Get lP”.
XAML Code
- <phone:PhoneApplicationPage
- x:Class="IPDemo.MainPage"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
- xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d"
- FontFamily="{StaticResource PhoneFontFamilyNormal}"
- FontSize="{StaticResource PhoneFontSizeNormal}"
- Foreground="{StaticResource PhoneForegroundBrush}"
- SupportedOrientations="Portrait" Orientation="Portrait"
- shell:SystemTray.IsVisible="True">
- <Grid x:Name="LayoutRoot" Background="Transparent">
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="*"/>
- </Grid.RowDefinitions>
- <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
- <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
- <TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
- </StackPanel>
- <Grid x:Name="GetIP" Grid.Row="1" Margin="12,0,12,0">
- <Button Content="Get IP" HorizontalAlignment="Left" Margin="144,185,0,0" VerticalAlignment="Top" Click="Button_Click"/>
- </Grid>
- </Grid>
- </phone:PhoneApplicationPage>
Next we need to enable ID_CAP_NETWORKING. Open the WMAppManifest file and enable ID_CAP_NETWORKING as shown in the following screen.
![WMAppManifest]()
Note that it is possible for there to be multiple network interfaces on your Windows Phone. For example, the Windows Phone Emulator has 3 network interfaces. The following code snippet tries to retrieve the first one in the List.
Now go to the code behind page.
C# Code
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- IPAddress objIPaddress = GetIPs();
- MessageBox.Show(objIPaddress.ToString());
- }
- public IPAddress GetIPs()
- {
- List<string> ipaddress = new List<string>();
- var hostlist = Windows.Networking.Connectivity.NetworkInformation.GetHostNames().ToList();
- foreach(var host in hostlist)
- {
- string ip = host.DisplayName;
- ipaddress.Add(ip);
- }
- IPAddress address = IPAddress.Parse(ipaddress.Last());
- return address;
- }
Now run your application. The output looks as in following screen:
![output]()