Localhost for Xamarin

Localhost for Xamarin

When running our apps in development environment we often want to access some kind of backed service running on our development machine. It is simple on iOS simulator because it uses host machine network so we can reach our development machine with localhost or On Android there is an alias to your host loopback interface. But when running on device we have to use actual IP address of our machine in local network. A lot of different variations, right? Localhost allows us to use different IP address to access local development machine depending on the platform the app runs on. There are 4 supported platform variations: iOS simulator, iOS device, Android emulator and Android device. This library takes advantage of bait-and-switch pattern so it can be used from shared code.

Note that nuget package has to be installed in both PCL and platform specific projects.


[code language=”csharp” gutter=”false”]
// Get IP address for current platform variation
string ip = CrossLocalhost.Current.Ip;

// Set IP address that must be used when running on iOS simulator

// Set IP address that must be used when running on iOS device

// Set IP address that must be used when running on Android emulator

// Set IP address that must be used when running on Android device

Default Values

These are the default values for each platform variation:

iOS simulator iOS device Android emulator Android device

But you can override them like shown in API section.


So now we are able to define different IP addresses for each configuration variant in one place in PCL (or in platform-specific code if we want to). And by calling CrossLocalhost.Current.Ip we will get the correct version based on the platform our app currently runs on.

This is the nuget package for this library and source code is available here. Have fun!

Hi, my name is Andrius. Welcome to my blog! I'm freelance mobile (C# Xamarin) developer currently learning Swift. I also do some ASP.NET Core Web API work as well. I blog mostly about work related subjects. If you would like to contact me for any reason shoot me an email at andrius [at] applications.lt

Site Footer