3

In my flutter app I am using the flask server for testing purpose. I started my server and run the API url in my flutter app. But SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 127.0.0.1, port = 44164. error is showing.

var headers = {'Content-Type': 'application/json'};
      var request =
          http.Request('POST', Uri.parse('http://127.0.0.1:5000/addrec'));
      request.body = json.encode({
        "name": UploadedName,
        "grade": Uploadedgrade,
        "loaction": Uploadedlocation,
        "like": Uploadedlike,
        "admission": Uploadedadmission,
        "comments": Uploadedcomments,
        "entery_time": UploadeddataentryTime
      });
      request.headers.addAll(headers);

      http.StreamedResponse response = await request.send();

      if (response.statusCode == 200) {
        print(await response.stream.bytesToString());
      } else {
        print(response.reasonPhrase);
      }

I am using actual android device for app running.

  • Does this answer your question? [SocketException: OS Error: Connection refused, errno = 111 in flutter using django backend](https://stackoverflow.com/questions/55785581/socketexception-os-error-connection-refused-errno-111-in-flutter-using-djan) – user18309290 Aug 05 '22 at 05:24
  • I am running server locally in my PC and I am using android device not emulator. – Krishna prasad Aug 05 '22 at 05:29
  • then u can use ur ipaddress with the port – Codertjay Oct 19 '22 at 03:55

2 Answers2

5

This happens because the localhost (or 127.0.0.1) on the device is only accessible to the device itself.

Solution 1

You can reverse-proxy a localhost port to the Android device/emulator running adb reverse on the command prompt like so:

adb reverse tcp:5000 tcp:5000

Solution 2

Use the machine's IP address where the API is running. Also, the API should be listening to the IP 0.0.0.0 to be accessible outside the localhost.

Supposing the API machine's IP is 192.168.1.123 it's going to be something like:

Uri.parse('http://192.168.1.123:5000/addrec')

Just take care because changing the API to listen to 0.0.0.0 is a security risk as the API is going to be accessible to the outside world.

lepsch
  • 8,927
  • 5
  • 24
  • 44
0

There is another way as far as you use the python server with dynamic ip 0.0.0.0:port

you can just use linux shell

ipconfig

or windows is

ifconfig

to get ur pc ipaddress and access the port

then you use the

ipaddress:port

Codertjay
  • 588
  • 8
  • 13