Accessing localhost:port from Android emulator
Asked Answered
E

26

333

I'm running a web service on my local machine that runs at localhost:54722.

I want to call the service from an app running in the Android emulator.

I read that using 10.0.2.2 in the app would access localhost, but it doesn't seem to work with the port number as well. It says HttpResponseException: Bad Request.

Executor answered 20/7, 2011 at 10:38 Comment(3)
Related: How can i access my localhost from my android device?Varden
I expected the behaviour, that not all ports are forwarded... 5555 was not forwarded but 8080 and 8081 worked just fine...Cocke
You need to edit your vs-iis config file: https://mcmap.net/q/100574/-android-quot-bad-request-invalid-hostname-quot-when-accessing-localhost-from-emulatorsPiranha
I
544

You can access your host machine with the IP address "10.0.2.2".

This has been designed in this way by the Android team. So your webserver can perfectly run at localhost and from your Android app you can access it via "http://10.0.2.2:<hostport>".

If your emulator must access the internet through a proxy server, you can configure a custom HTTP proxy from the emulator's Extended controls screen. With the emulator open, click More dots, and then click Settings and Proxy. From here, you can define your own HTTP proxy settings. screen-shot for HTTP config

Immunotherapy answered 1/3, 2012 at 11:33 Comment(14)
Why should it? The error Bad Request means that the localhost server is reachable, but that the request isn't quite correct..Douai
i am not sure, i follow through, what exactly are you saying, is it relevant to provided solution??Immunotherapy
Not working for me right now, but here's the link to the Android docs and it's clear that this is what sould do it (10.0.2.2); developer.android.com/tools/devices/emulator.htmlRetrospection
obviously this does not clarify anything, Robin is already using 10.0.2.2 ip in the question and it is not working. Although your answer is correct, it does NOT provide a solution.Luben
I too get 400: Bad request error with same solution.Sinotibetan
@KevalPatel there might be problem with your request that you are sending to server. try to print request object on both client and server side to get clarityImmunotherapy
I was running application on localhost and not added it on IIS, I am not sure why but after adding service on IIS, it's working. And ya, my properties are same in android and server app. ThanksSinotibetan
This works to route the request, but won't work past login for multi-tenant (wildcard subdomain) dependant apps.Rescind
+1 that is should be the accepted answer. For those who want to intercept Android Emulator traffic with something like a Burp proxy, this is the information I was looking for - 10.0.2.2. It answers the main question; the BadRequest is likely to be an orthogonal issue.Vervain
This answer itself is perfect. Most remaining issues like 400 are caused by the web server on the host. Servers such as IIS Express require extra configuration, as I documented in blog.lextudio.com/…Steam
This answer rounded out the solution for me and got me up and running: https://mcmap.net/q/86497/-how-do-you-connect-localhost-in-the-android-emulator-duplicateDecorate
In API 28+ you should explicitly allow non-https (clear-text) traffic in your network config too. See my answer below https://mcmap.net/q/98328/-accessing-localhost-port-from-android-emulatorRuthenian
My Android Studio is 2021.2.1 Patch1. I cannot find the proxy tab in My emulator settings.Latif
What if my localhost has another hostname?Fakir
S
87

Use 10.0.2.2 for default AVD and 10.0.3.2 for Genymotion

Sesquiplane answered 27/9, 2014 at 6:43 Comment(4)
Why 10.0.3.2 for Genymotion ?Stage
@Stage Because Genymotion is a different emulator and they chose to use a different ip than google's emulator (Which borders on useless. Seriously, when are they going to do something about their awful default emulator?)Recor
In API 28+ you should explicitly allow non-https (clear-text) traffic in your network config too. See my answer below https://mcmap.net/q/98328/-accessing-localhost-port-from-android-emulatorRuthenian
Some Emulator don't work on AVD, I had to delete and reinstall another one in order to make this 10.0.2.2 worksGastight
R
46

Since 10.0.2.2 is not a secure domain for Android you have to allow non-secured domains in your network configuration for API 28+ where non-TLS connections are prevented by default.

You may use my following configurations:

Create a new file in main/res/xml/network_security_config.xml as:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

And point it in AndroidManifest.xml

<application
......
......
android:networkSecurityConfig="@xml/network_security_config">
Ruthenian answered 26/6, 2019 at 9:44 Comment(3)
I'd say this is the correct answer, although it is much easier achieved, adding this to your manifest (as proposed here: #51903129 ) : <application android:usesCleartextTraffic="true"> </application>Unmeriting
If you're using API > 28, check out this answer, this should solve your issue.Doradorado
I don't know the ip and port. i have my local server running at m.local.sese.com . How do I access it in my emulator?Hexameter
I
39

I'm not sure this solution will work for every Android Emulator and every Android SDK version out there but running the following did the trick for me.

adb reverse tcp:54722 tcp:54722

You'll need to have your emulator up an running and then you'll be able to hit localhost:54722 inside the running emulator device successfully.

Improvised answered 5/11, 2020 at 18:35 Comment(1)
The easiest one for me. Saved it right to an npm script "android-map-localhost": "adb reverse tcp:54722 tcp:54722"!Ethyl
S
32

I faced the same issue on Visual Studio executing an web app on IIS Express. to fix it you need to go to your project properties then click on Debug Tab and change http://localhost:[YOUR PORT] to http://127.0.0.1:[YOUR PORT] and set the android url to http://10.0.2.2:[YOUR PORT]. it worked for me.

Sides answered 30/10, 2017 at 14:54 Comment(6)
this in conjunction with the 10.0.0.2 url solved it for me. this setting seemed to be overriding the hosting.json approach explained elsewhere.Abscond
I'm running django server locally on macOS and usually I access it via http://localhost:5000/ in both Postman and iOS simulator. This solution works for Android simulator and no need to modify my server, nor any settings in simulator. Quick, nice and portable to other computers without extra work.Laufer
Android app with xamarin and ASP.NET Web APIs both using VS. WORKED! Thanks!!Ouphe
This is the easiest way...it worked for me while trying to connect to my api rest developed with .net core 3.1 on VS 2019 from my emulator...Thanks!Rabblement
This also worked for me. One thing I initially overlooked was that .NET Core sets the applicationURL to https, this solution uses http and worked after changing it as such.Arlynearlynne
android: "10.0.2.2:57738"; api: 127.0.0.1:57738/swagger/index.htmlBulbiferous
O
19

If you are using IIS Express you may need to bind to all hostnames instead of just `localhost'. Check this fine answer:

https://mcmap.net/q/73476/-how-to-enable-external-request-in-iis-express

Tell IIS Express itself to bind to all ip addresses and hostnames. In your .config file (typically %userprofile%\My Documents\IISExpress\config\applicationhost.config, or $(solutionDir).vs\config\applicationhost.config for Visual Studio 2015), find your site's binding element, and add

<binding protocol="http" bindingInformation="*:8080:*" />

Make sure to add it as a second binding instead of modifying the existing one or VS will just re-add a new site appended with a (1) Also, you may need to run VS as an administrator.

Onceover answered 22/1, 2016 at 17:45 Comment(4)
No, you don't always need to use blank host name, blog.lextudio.com/…Steam
<binding protocol="http" bindingInformation="*:15000:127.0.0.1" /> this was the way IIS Express liked where 15000 was my port and then pointing to 10.0.2.2:15000 on the android emulatorHackett
After trying different options this solution is the only one that has worked! Many thanksEckhart
No work! If I modify the port of the file and then the web server cannot run.Latif
C
16

I solved it with the installation of "Conveyor by Keyoti" in Visual Studio Professional 2015. Conveyor generate a REMOTE address (your IP) with a port (45455) that enable external request. Example:

enter image description here

Conveyor allows you test web applications from from external tablets and phones on your network or from Android emulators (without http://10.0.2.2:<hostport>)

The steps are in the following link :

https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.ConveyorbyKeyoti

Cootie answered 19/6, 2017 at 20:2 Comment(3)
What if you don't run the webserver within Visual Studio? Imo, this isn't an answer to the question.Razor
I try but after some days later the given URL is not working and don't find any soluations.Confiteor
After a long struggle, the only thing that did the trick was installing this extension and enabling the Remote URL feature. It takes the request a bit longer to hit the API, but it works.Catercorner
C
14

After running your local host you get http://localhost:[port number]/ here you found your port number.

Then get your IP address from Command, Open your windows command and type ipconfig enter image description here

In my case, IP was 192.168.10.33 so my URL will be http://192.168.10.33:[port number]/. In Android, the studio uses this URL as your URL. And after that set your URL and your port number in manual proxy for the emulator.

enter image description here

Confiteor answered 15/11, 2018 at 9:38 Comment(1)
My Android Studio is Chipmunk| 2021.2.1 Patch1. And My Emulator Settings does not have proxy tab. Could you tell me what version of your Android Studio ? Or is there a way to solve this problem?Latif
S
13

The problem is that the Android emulator maps 10.0.2.2 to 127.0.0.1, not to localhost. So configure your web server to serveron 127.0.0.1:54722 and not localhost:54722. That should do it.

Smarmy answered 19/9, 2017 at 13:15 Comment(0)
H
11

I have a webserver running on my localhost.

If I open up the emulator and want to connect to my localhost I am using 192.168.x.x. This means you should use your local lan ip address. By the way, your HttpResponseException (Bad Request) doesn't mean that the host is not reachable.

Some other errors lead to this exception.

Hybrid answered 20/7, 2011 at 10:56 Comment(0)
V
8

To access localhost on Android Emulator

  • Add the internet permission from AndroidManifest.xml
    <uses-permission android:name="android.permission.INTERNET" />

  • Add android:usesCleartextTraffic="true", more details here:

  • Run the below-mentioned command to find your system IP address:

ifconfig | grep "inet " | grep -v 127.0.0.1

Copy the IP address obtained from this step (A)

  • Run your backend application, which you can access at localhost or 127.0.0.1 from your sytem.

  • Now in android studio, you can replace the URL if you're using in code or You can use the ip address obtained from step(A) and try opening in web browser, Like this http://192.168.0.102:8080/

Don't forget to add PORT after the IP address, in my case app was running on 8080 port so I added IP obtained in (A) with the port 8080

Vulturine answered 9/6, 2020 at 19:15 Comment(2)
Hey, this worked! but is there any way to have this set up permanently so that I don't have to change it every time? I'd rather not have to look up my IP every time and just have the emulator recognize that localhost means the host machine.Underestimate
If you're worried of changing in code every-time, better to have a hostname there that you can resolve locally. So that there will be no code change, and the IP will be resolved locally. This link might be helpful tecmint.com/setup-local-dns-using-etc-hosts-file-in-linux for setting up host to resolve locally. To make this flow automatically, I didn't find any :)Vulturine
P
4

"BadRequest" is an error which usually got send by the server itself, see rfc 2616

10.4.1 400 Bad Request

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

So you got a working connection to the server, but your request doesn't fit the expecet form. I don't know how you create the connection, what headers are included (if there are any) – but thats what you should checking for.

If you need more help about, explain what your code is about and what it uses to connect to the Server, so we have the big picture.

Here is a question with the same Problem – the answer was that the content-type wasnt set in the header.

Photomicrograph answered 23/7, 2012 at 11:59 Comment(1)
You got the right point, but went the wrong direction afterwards. The next step should be analyzing the server to learn what kind of requests it cares about, so as to understand why requests from the emulators are replied with 400. A case study for IIS Express can be found here, blog.lextudio.com/…Steam
S
3

you need to set URL as 10.0.2.2:portNr

portNr = the given port by ASP.NET Development Server my current service is running on localhost:3229/Service.svc

so my url is 10.0.2.2:3229

i'd fixed my problem this way

i hope it helps...

Shadrach answered 6/12, 2012 at 10:9 Comment(2)
I have a custom url for my localhost and I don't know the port number. This is my url m.local.sese.com .Hexameter
I believe in this case you need to set portNr on DNS for that domainShadrach
E
3

1) Run ipconfig command in cmd

2) You will get result like this enter image description here

3) Then use IPv4 Address of VMWare Network Adapter 1 followed by port number

In My Case its 8080, so instead of using localhost:8080

I am using 192.168.56.1:8080

enter image description here

Done.....

Enlistee answered 13/4, 2018 at 6:25 Comment(1)
Port number is what you set in xamp apache portCongeries
B
2

I am using Windows 10 as my development platform, accessing 10.0.2.2:port in my emulator is not working as expected, and the same result for other solutions in this question as well.

After several hours of digging, I found that if you add -writable-system argument to the emulator startup command, things will just work.

You have to start an emulator via command line like below:

 emulator.exe -avd <emulator_name> -writable-system

Then in your emulator, you can access your API service running on host machine, using LAN IP address and binding port:

http://192.168.1.2:<port>

Hope this helps you out.

About start emulator from command line: https://developer.android.com/studio/run/emulator-commandline.

Brewage answered 4/7, 2019 at 9:16 Comment(0)
B
2

Explanation why localhost is not available from emulators for anyone who has basic access problem. For sophisticated cases read other answers.

Problem: Emulator has own local network and localhost maps itself to emulator, but NOT your host!

Solution:

  1. Bind your server to 0.0.0.0 to make it available for emulator's network
  2. Get external IP address of your laptop: ifconfig command for Mac
  3. In Android (or Flutter app) use IP address of your external interface like: 192.168.1.10 instead of localhost
Bireme answered 22/10, 2019 at 16:43 Comment(0)
N
2

I had the same issue when I was trying to connect to my IIS .NET Webservice from the Android emulator.

  1. install npm install -g iisexpress-proxy
  2. iisexpress-proxy 53990 to 9000 to proxy IIS express port to 9000 and access port 9000 from emulator like "http://10.0.2.2:9000"

the reason seems to be by default, IIS Express doesn't allow connections from network https://forums.asp.net/t/2125232.aspx?Bad+Request+Invalid+Hostname+when+accessing+localhost+Web+API+or+Web+App+from+across+LAN

Nadianadine answered 7/12, 2019 at 19:26 Comment(0)
S
1

I would like to show you the way I access IISExpress Web APIs from my Android Emulator. I'm using Visual Studio 2015. And I call the Android Emulator from Android Studio.

All of what I need to do is adding the following line to the binding configuration in my applicationhost.config file

<binding protocol="http" bindingInformation="*:<your-port>:" />

Then I check and use the IP4 Address to access my API from Android emulator

Requirement: you must run Visual Studio as Administrator. This post gives a perfect way to do this.

For more details, please visit my post on github

Hope this helps.

Slake answered 24/2, 2017 at 5:31 Comment(2)
Or install the free VS Extension called Conveyor from the Extensions window. That opens up IIS Express to outside requests without changing the config.Queenie
You do have other options, blog.lextudio.com/… than running VS as admin. So I won't call that a must.Steam
G
1

For Laravel Homestead Users: If anyone using Laravel with homestead you can access app backend using 192.168.10.10 in emulator

Still not working? Another good solution is to use ngrok https://ngrok.com/

Gandzha answered 11/1, 2018 at 17:49 Comment(1)
ngrok can only be run on internet, slow internet may cause network failure request.Ayo
F
1

What worked for me was doing these 2 things:

  1. Disable the redirect to https. When I try to access http port from localhost it was redirecting to https by default. Disable it by either removing the https configuration for local or disabling redirect for your OS.
  2. Disable firewall. There are different layers of firewall settings these days. Check if you can be specific about the ports or app that can be bypassed from the firewall.
Fuselage answered 10/5, 2023 at 14:7 Comment(0)
O
0

localhost seemed to be working fine in my emulator at start and then i started getting connection refused exception i used 127.0.2.2 from the emulator browser and it worked and when i used this in my android app in emulator it again started showing the connection refused problem.

then i did ifconfig and i used the ip 192.168.2.2 and it worked perfectly

Obligation answered 17/1, 2014 at 11:38 Comment(0)
T
0

Bad request generally means the format of the data you are sending is incorrect. May be mismatched data mapping . If you are getting bad request implies you are able to connect to the server, but the request is not being sent properly.

Tufted answered 6/9, 2016 at 5:36 Comment(0)
C
0

If anybody is still looking for this, this is how it worked for me.

You need to find the IP of your machine with respect to the device/emulator you are connected. For Emulators on of the way is by following below steps;

  1. Go to VM Virtual box -> select connected device in the list.
  2. Select Settings ->Network-> Find out to which network the device is attached. For me it was 'VirtualBox Host-Only Ethernet Adapter #2'.
  3. In virtualbox go to Files->Preferences->Network->Host-Only Networks, and find out the IPv4 for the network specified in above step. (By Hovering you will get the info)

Provide this IP to access the localhost from emulator. The Port is same as you have provided while running/publishing your services.

Note #1 : Make sure you have taken care of firewalls and inbound rules.

Note #2 : Please check this IP after you restart your machine. For some reason, even If I provided "Use the following IP" The Host-Only IP got changed.

Crowded answered 17/1, 2017 at 5:41 Comment(0)
I
0

I resolved exact the problem when the service layer is using Visual Studio IIS Express. Just point to 10.0.2.2:port wont work. Instead of messing around the IIS Express as mentioned by other posts, I just put a proxy in front of the IIS Express. For example, apache or nginx. The nginx.conf will look like

 # Mobile API
 server { 
    listen       8090;
    server_name  default_server;

    location / {
        proxy_pass http://localhost:54722;
    }
  }

Then the android needs to points to my IP address as 192.168.x.x:8090

Italy answered 8/5, 2017 at 20:7 Comment(0)
B
0

if you are using some 3rd party package like node express or angular-cli you will need to find the IP of your machine, and attach your host to that IP within the server startup config (instead of localhost). Then launch it from the emulator using the IP. For example, I had to use: ng serve -H 10.149.212.104 to use the angular-cli. Then from the emulator I used: http://10.149.212.104:4200

Besiege answered 16/8, 2017 at 0:39 Comment(0)
P
-1

If you are working with Asp.Net Web API, in .vs/config folder inside your project, modify these lines as per you port setting. Let suppose you use port 1234 and physicalPath to the project folder set by IIS is "D:\My Projects\YourSiteName", then

<site name="YourSiteName" id="1">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="D:\My Projects\YourSiteName" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:1234:*" />
                </bindings>
            </site>

In android studio, access your api with "http://10.0.2.2:1234" ...

Peril answered 1/3, 2021 at 4:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.