Access localhost from Android virtual machine

Whilst playing with Xamarin I encountered an issue when debugging the Android version of the app. Apparently localhost is not translated causing an error when trying to access an API running on my development machine. Strangely I did not encounter this issue when debugging the IOS version of my app.

To access your localhost (aka your development machine) you need to refer to the IP-address 10.0.2.2.

To work around this issue you can use the DeviceInfo class from Xamarin.Essentials. Just add a statement which checks the type of device the code is being ran on.

string baseAddress =
DeviceInfo.Platform == DevicePlatform.Android ? "http://10.0.2.2:25026/file" : "http://localhost:25026/file";

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: