Receiving data from localhost throws 'Connection Refused Error' [duplicate] - sockets

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.

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 , and then click Settings and Proxy. From here, you can define your own HTTP proxy settings.

Use 10.0.2.2 for default AVD and 10.0.3.2 for Genymotion

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">

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.

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.

If you are using IIS Express you may need to bind to all hostnames instead of just `localhost'. Check this fine answer:
https://stackoverflow.com/a/15809698/383761
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.

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:
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

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.

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
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.

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.

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

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...

"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.

1) Run ipconfig command in cmd
2) You will get result like this
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
Done.....

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.

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/

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.

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:
Bind your server to 0.0.0.0 to make it available for emulator's network
Get external IP address of your laptop: ifconfig command for Mac
In Android (or Flutter app) use IP address of your external interface like: 192.168.1.10 instead of localhost

I had the same issue when I was trying to connect to my IIS .NET Webservice from the Android emulator.
install npm install -g iisexpress-proxy
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

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

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.

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;
Go to VM Virtual box -> select connected device in the list.
Select Settings ->Network-> Find out to which network the device is attached. For me it was 'VirtualBox Host-Only Ethernet Adapter #2'.
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.

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

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

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" ...

Related

Sideloading Word JS Addin developed on local Docker machine - Can't reach Add-in

I'm having trouble trying to side-load an add-in in MS Word, getting the error
'ADD-IN ERROR: A problem occured while trying to reach this add-in.' The add-in needs to be hosted on a local docker environment to be integrated in the rest of a web aplication.
Setup
The add-in files are hosted on a local docker machine, accessible through both an ip-address and a https://dev.local address. The add-in is reachable through Internet Explorer and Edge Chromium without any certificate errors. It doesn't matter whether I try to reach the IP address of the locally mapped dev.local, the add-in refuses to load and just crashes. I'm on Word version 2002 build 12527.20194. Another word-addin that we host externally works fine.
What i've tried
I've been messing around with the settings in Internet Explorer (moving the sites to local zone, trusted zone, enabling and disabling the protection there).
I've upgraded Edge to edge Chromium. I've tried to use the Preview of
Edge Developer Tools, but that crashes when the error occurs.
I've tried using Fiddler and activate the runtime logging, but can't get more information on what's going wrong.
I've used the Yoman validation on the manifest.xml and everything checks out.
I've also enabled loopback through CheckNetIsolation LoopbackExempt -a -n="microsoft.win32webviewhost_cw5n1h2txyewy"
I'm pretty much at a loss now: what can I do to get more information on what's crashing the add-in?
OK so I managed to finally get this to work, leaving this here for anyone who might run into the same issues.
Because the local sideloading did work, I figured we needed to emulate the localhost situation with the docker. So I instructed the virtual machine to forward localhost:3000 to the Docker Toolbox port 443. I also copied over the SSL certificates generated by Yoman in <userhome>/.office-addin-dev-certs to the Nginx docker and instructed Nginx to use those SSL certificates for port 443.
I'm not entirely sure if adapting all of the other settings (such as enabling the loopback interface and using the about:flags page to always allow https on localhost are also neccesary, maybe just emulating the webserver on localhost is enough. Hope this helps someone!

Install pwa in smartphone with localhost

I have a pwa and with localhost I can install on desktop, but I can't with my samrtphone andorid. Is it possible install a pwa without upload in a http server?
UPDATE:
I founded a work around that works, I putted a server on a port on my android smartphone using Dory - node.js (I have installed also express package)
https://play.google.com/store/apps/details?id=io.tempage.dorynode
Opening chrome in that port I see the "add to home screen popup".
This is unfortunately not an entire solution but an advice on where to look:
Make sure you are in the same wifi network with your Desktop and your phone.
Find out the local IP address of the Desktop PC (probably something like 192.168.0.x). You can find it under ipconfig (Windows) or ifconfig (Unix)
Host your PWA with the http server (remember to use ssl)
Try to access your hosted website from the phones browser, using the IP address and the port, probably something like 192.168.0.x:8080
If you serve your web page through another port (ex. 3000) make sure you configure Port Forwarding through your Router default config IP address
You should be able to open the website. So far I was not able to call the install event, but I will update my answer if I find out more.

Why can't I enter the url on my phone's browser to view my live site?

I use an extension called Live Server in Visual Studio Code. When I run live, the browser opens and the url is http://127.0.0.1:5500/index.html. Why can't I open this url on my phone's browser to see the live site on the phone. Is there a way to do this (Live reload on phone and browser)?
Note: I also develop using ionic and when I ionic serve I can see it on browser and when I open the ionic dev app (not ionic view!), I can see the live app on the phone. I can view it on multiple devices with the condition of all devices being in the same network which I am fine with.
127.0.0.1 is a special-purpose IPv4 address reserved for loopback purposes. That is, this IP refers to your computer itself.
By entering http://127.0.0.1:5500/index.html in your browser, you're requesting web page within your computer.
In normal case, your computer will be in a NAT network (under same wi-fi AP for instance), and you'll be assigned with a virtual IP. Normally it's 192.168.x.x.
You may enter the following command in your command prompt to see your IP address.
ipconfig
If you're using Mac or Linux, use this instead.
ifconfig
As a result, under your network interface card, you'll get your IP Address.
If the IP address belongs to virtual IP, then you may access it with your phone using
http://< Your IP Address >:5500/index.html
If it's not virtual IP, it is Public IP. Then, you'll have to configure appropriate Firewall settings under this circumstance.
Hope this will help.
You cannot open the same url on your phone, because that url host (127.0.0.1) refers to the localhost (the same machine).
If your phone and server are on the same network, you can replace the current host with the servers local IP.
So if your servers local IP is: 192.168.0.36
the URL you enter in your phone should be http://192.168.0.36:5500/index.html.
I had a same problem.
Solution: Control Panel -> Windows Defender Firewall -> Allow an app or feature through Windows Defender Firewall -> Allowed "code.exe" app.
Run ipconfig and find your private IP.
Make sure your phone is on the same network.
go to http://192.168.0.***:5500/
Open Live server's settings.json and add these two settings "liveServer.settings.useLocalIp": true and "liveServer.settings.host": "localhost". Then type your localhost ip in your mobile browser (in my case it was 192.168.0.110) with the rest of the Live server URL i.e. 192.168.0.110:5500/index.html. This worked for me.
Let me clear this out for you. we call localhost or 127.0.0.1 as loop backs. which will itself point to the same machine(means that particular service should also be hosted in the same machine). what Microsoft did with visual studio live share is that if have the live share extension it will create a reverse proxy between the host(where the server is hosted) and the target (In this case your browser) which means even though your host is in a different country the extension will tunnel the transparent proxy to your loop-back address. visual studio live share extension is what you phone doesn't have and Microsoft doesn't support yet. If you still want to access your local service what you can do is turn off the firewall(or pass through that particular port where ur service is hosted) and connect your phone to the same network as your machine with the service running and instead using http://127.0.0.1:5500/index.html use http:// UR SERVER IP :5500/index.html you can get UR SERVER IP by giving ipconfig in windows command prompt or ifconfig if ur server is on linux.

Connect an Android Device To a Web Service on Local Host

I implemented a web service for an Android application. The web service is running on my local host (192.168.1.2). Using the Android emulator I succeeded to connect to web service. The I tried to connect my Android device using debugging mode to web service but it didn't work. So my question is if it is possible to connect an Android device to this web service that is running on my local host (192.168.1.2) without using a real IP ?
It's much simpler way supported by google!
Connect your phone via usb to computer and enable usb debugging
On your computer open Chrome browser and type exactly this address: chrome://inspect/#devices
Now you can link your computer port to your device port by port forwarding button. On my computer I have service on address localhost:61437 and I just linked it to device's 8081 port. Remeber to check 'Enable port forwarding' checkbox
screen from service on my computer ( localhost:61437 )
screen from my mobile browser with the same service ( localhost:8081). And that's it. Also you use this service address in your application
Did you already solve your problem? I also got a problem like you. These are the steps that I already done:
unplug lan cable or turn off any other internet connection from your pc.
connect your android mobile to your pc using usb.
turn on usb tethering
back to your pc. check your ip. mine is 192.168.42.37
check your webservice app in your pc. let's say http://192.168.42.37/webserviceapp
back to your android mobile. try this url http://192.168.42.37/webserviceapp
Now you can access your webservice app in your pc from your mobile phone.
Well your localhost is 127.0.0.1 (or ::1) and your LAN IP is 192.168.1.2. Each pc/device that are connected under your LAN could reach your webservice on IP 192.168.1.2
Your Android device must be so connected under the same LAN maybe through Wifi connection so it will be able to talk with 192.168.1.2.
If you can't connect your Android device under the same LAN eg you have just a 3g connection you need to play with your router/firewall to redirect all incoming traffic (maybe just the http traffic) from your public ip to you private ip (192.168.1.2)
Hope this help
I'll throw in my process, since nothing on SO worked for me. Here are the steps I took to connect my physical android device to the web service running on my laptop (connected to the phone) on localhost:
Enable USB debugging on your Android device
Run your web service on your machine. My web service runs on localhost, port 3000 in development: http://localhost:3000/api/...
Run ifconfig (Unix), or ipconfig (Windows)
Find your machine's inet address on your LAN interface. Mine is 10.0.0.121 for interface wlan0. Externally, it is 68.43.XX.XXX, which is not the address that you want to use.
Use the LAN IP since you are connecting to your service on LAN, otherwise you might get an econnrefused (connection refused) error due to firewall rules
Build your http URL with that IP address, and the port that your web service is running on. For me, it's http://10.0.0.121:3000/api/...
When you launch your app, you should connections to your local web service in logs, Wireshark, etc, and you should see the desired activity/data in your Android application.
I had the same issues, researched a lot then found out that you have to explicitly make changes in your firewall settings. Your firewall is blocking your code to be accessed from external source. So, all you need to do is, go to firewall settings, add port 80 (in my case since, I am using Apache http Server) for inbound and outbound. Now, you can test it on your phone's browser http://192.16..**:80/
I've done that on a Mac using GasMask and Charles Proxy Server. Your phone and your computer have to be on the same network.
say the webservice url you want to access is at http://api.xyz.com, you first use GasMask to point that url to your localhost, then use Charles to set up a proxy server. Then you go to the settings on your phone, go into Wi-Fi, long-press the network you are connected to, choose Modify Network, and enter the proxy settings Charles gave you.
In my case, nothing of these solutions works because Windows firewall blocks it, but putting a rule on the firewall hasn't effect.
The problem in my case is that my laptop is connected with Wifi and Windows had the Wifi connection like a Public network. I must to change the network connection to Private network. http://www.comofuncionatodo.net/tecnologia/informatica/como-cambiar-de-red-publica-a-red-privada-en-windows-10/
I agree with the other answers as good approaches if you don't want to expose your DEV webservice on the internet. However, it's much easier if you do just expose the webservice. There's a number of free DNS services, but I've found no-ip to be the easiest to set up. I use it for exactly the purpose that you asked about; so I can test with my DEV webservice on a real device.
If you choose to go with no-ip (I have no affiliation with that company, it's just the one I've used and am familiar with), you can get a free publicly accessible URL like http://MyExampleWebServer.no-ip-org, and no-ip has a utility you can install so even if you're behind a dynamic IP, it will always keep the correct external IP associated with that URL. If you're working from your house, then you'd just need to make sure you port forward traffic from port 80 to your internal 192.x.x.x IP address (or whatever port you use; maybe 443 for ssl).
It's as easy as that, and now you can hit that webservice from any device that can access the internet.
I haven't worked with it, but I believe dyndns also offers a similar service.
This solution is for GAE development server in Eclipse
Step 1: Get the LAN IP
Goto your Windows Command Console (Press Win+R, then type "cmd"). In the console, enter "ipconfig". You will see a list of display. Under Wireless LAN adapter Wi-Fi, get the IPv4 Address. It will be something 192.168.x.x
LAN IP : 192.168.x.x
Step 2:
Go to Eclipse, Open the Configured server
Under Properties of GAE Development Server -> Local Interface address to bind to, enter the LAN IP address, and save.
Step 3:
Now you can access the GAE server by
http://192.168.x.x:8888/
8888 - Refers to the Port Number, as mentioned in the GAE development server
In order to access local web services using their own server hosts rather than IP addresses with ports, do these following steps:
Make sure your Android device and your local machine are on the same network.
Install SquidMan on your Mac, Linux, or any other Proxy Server.
Configure the proxy server's HTTPPort (ex. 5555) and clients (ex. 192.168.0.0/24) to your own network mask, and run the proxy server.
You are either using the web services in:
a. A web browser: Configure the proxy settings of your Android device from Modify WiFi networks.
b. Android application:
Set up the Proxy for your HTTP client. If you are using Volley, check this out: Volley Behind a Proxy server.
You can now connect to it by using whatever URL you are using on your host to connect to the web service (ex. http://my-local-machine.com)
Hint: If you got 4xx response codes, make sure your web service allows connections from other non-local-hosts.
If you are referring your localhost on your system from the Android emulator then you have to use
http://10.0.2.2:8080/
Because Android emulator runs inside a Virtual Machine(QEMU) therefore here 127.0.0.1 or localhost will be emulator's own loopback address.

How do you connect localhost in the Android emulator? [duplicate]

This question already has answers here:
How to connect to my http://localhost web server from Android Emulator
(17 answers)
Closed 2 years ago.
I have made a php script inside localhost and I am connecting that with httpClient but I am getting a problem.
Please tell me how can I connect to a php file at localhost from the emulator?
Use 10.0.2.2 to access your actual machine.
As you've learned, when you use the emulator, localhost (127.0.0.1) refers to the device's own loopback service, not the one on your machine as you may expect.
You can use 10.0.2.2 to access your actual machine, it is an alias set up to help in development.
Use 10.0.2.2 for default AVD and 10.0.3.2 for Genymotion
Thanks, #lampShaded for your answer.
In your API/URL directly use http://10.0.2.2:[your port]/ and under emulator setting add the proxy address as 10.0.2.2 with the port number. For more, you can visit: https://developer.android.com/studio/run/emulator-networking.html
This is what finally worked for me.
Backend running on localhost:8080
Fetch your IP address (ipconfig on Windows)
Configure your Android emulator's proxy to use your IP address as host name and the port your backend is running on as port (in my case: 192.168.1.86:8080
Have your Android app send requests to the same URL (192.168.1.86:8080) (sending requests to localhost, and http://10.0.2.2 did not work for me)
Thanks to author of this blog: https://bigdata-etl.com/solved-how-to-connect-from-android-emulator-to-application-on-localhost/
Defining network security config in xml
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">10.0.2.2</domain>
</domain-config>
</network-security-config>
And setting it on AndroidManifest.xml
<application
android:networkSecurityConfig="#xml/network_security_config"
</application>
Solved issue for me!
Please refer: https://developer.android.com/training/articles/security-config
you should change the adb port with this command:
adb reverse tcp:8880 tcp:8880; adb reverse tcp:8081 tcp:8081; adb reverse tcp:8881 tcp:8881
Instead of giving localhost give the IP.