SocketException: OS Error: Connection refused, errno = 111 in flutter using django backend

DjangoFlutterDjango Rest-FrameworkPythonanywhere

Django Problem Overview

I m building a flutter app with django rest-framework. The registration api is working fine in Postman but after some successful registration from the flutter app it is showing the above error. The request is been sent on https address.

Removed csrf. Nothing happens.


var data = {'email':signupemailidcontroller.text,
        //http request here
                        headers: headers,
                        body: json.encode(data))

Output in Console:

SocketException: OS Error: Connection refused, errno = 111

I Expect the response of this request to be a Json object containing the user and token.

Django Solutions

Solution 1 - Django

Harnish, need a few more details in-order to debug this error.

  1. Are you running the server locally or communicating with a remote server?
  2. Are you running the app on the Android Emulator?

Possible Solution:

If you're running the server locally and using the Android emulator, then your server endpoint should be instead of localhost:8000 as AVD uses as an alias to your host loopback interface (i.e) localhost

Note on Futures

I noticed above that the code is using await and then on the same line. This can be confusing, to be clear, await is used to suspend execution until a future completes, and then is a callback function to execute after a future completed. The same could be written as below

void myFunction() async {
    var data = {};
    var response = await, headers:headers, body:data);
    if (response.statusCode == 200) {
    } else {
       print('A network error occurred');

or the non async/await method

void myFunction() {
    var data = {};, headers:headers, body:data)
    .then((response) => print(response.body))
    .catchError((error) => print(error));

For a more detailed information on Futures in Dart please read

Solution 2 - Django

I went to the terminal and used ifconfig command

I got my IP address:

enter image description here

Then I simply replaced this IP address with my "localhost" in flutter app http requests. And it worked like a charm!

Solution 3 - Django

In addition to Rohan's answer you can also read:

I was trying to run my app on physical device using local server so, for that i had to use the below mentioned command, here keep in mind change the port number according to your own port number

adb reverse tcp:3001 tcp:3001

> As @maheshmnj pointed that this command is redirecting your phone's > port 3001 to your computer's port 3001. In case if you want to > redirect port 2000 of your phone to port 3000 of your computer then > you could do this adb reverse tcp:2000 tcp:3000

you can also read about adb and networking via going through below mentioned page

Solution 4 - Django

  • if in localhost instead localhost use the IP of your network
  • hint:for find Ip in cmd run ipconfig and get the ipv4

1: Example:

                    headers: headers,
                    body: json.encode(data))

if in server write the url of main in url

Solution 5 - Django

Try adding <uses-permission android:name="android.permission.INTERNET"/> to your manifest. This solved this issue for me.

Solution 6 - Django

I had the same problem running in a real device, and only changing the IP in API link doesn´t work.

The solution for me was to put the server run with the command below: runserver

Then pass your machine IP to the API link instead of localhost, as the sample below:

Solution 7 - Django

If you are using 'localhost' in your url, change it to your ipv4 address and it will work

Solution 8 - Django

This problem occurs when the endpoint are incorrect or your host and server backend (Example Laravel API)doesn't share the same IP address.

Solution is.

  1. Connect your workspace (computer, emulator, devices) in the same network.
  2. Find your IP by typing on terminal ifconfig.
  3. If you build your API with Laravel, start the server appointing to IP ADDRESS of your computer, sudo php artisan serve --host YOUR_COMPUTER_IP_ADDRESS --port NUMBER


`sudo php artisan serve --host --port 80`

4. Test your endpoint in Postman or similar Application and type 5. If everything is working good, you can run with app. Go!!!

Solution 9 - Django

In C#[.net core api], go to launchSettings.json under Properties tab and change the follwing code to this(change localhost to on applicationURl) and on the app(flutter), use ur local IPV4 IP. ex: (

"coreWebAPI": {
      "commandName": "Project",
      "launchBrowser": false,
      "launchUrl": "api/values",
      "applicationUrl": "", 
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"

Solution 10 - Django

This is what I had to change to fix the same error in my case:

  • Start django with python runserver 0:8000 and not just python runserver (0:8000 is the abbreviation for and makes your web application visible on your local network - see
  • In your flutter app specify the server address using your pc local ip, i.e. instead of http://localhost:8000 use something like To retrieve your current ip address run ipconfig in the terminal if on Windows, otherwise ifconfig.
  • Update allowed host in django settings if necessary. For example set ALLOWED_HOSTS = ['*', ] (but only in your dev environment!)

Solution 11 - Django

Soltuion that worked on my machine

[√] Flutter (Channel stable, 2.5.3, on Microsoft Windows [Version 10.0.19043.1288], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[√] Chrome - develop for the web
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.61.2)
[√] Connected device (3 available)

STEP: 1 (get your ipv4)

in terminal/cmd type

  • ifconfig for Mac/Linux/Unix
  • ipconfig for Windows

you will get some result in windows it looks like enter image description here

STEP: 2 (change your request url)

❌ Dont do

  • http.get('localhost/my-local-rest-api/etc'

✅ Do

  • for android http.get('
  • for ios http.get('


always pass Uri instead of raw String example: http.get(Uri.parse('my-url-in-raw-string'))

STEP 3: enable un-encrypted networking connections

for Android

in android/app/src/debug/AndroidManifest.xml

<manifest ...other params...>
   // STEP: 1 make sure you have INTERNET permission
   <uses-permission android:name="android.permission.INTERNET" />

        android:usesCleartextTraffic="true"> <-- STEP: 2 add this line

for iOS

in ios/Runner/Info.plist add this


Solution 12 - Django

I fixed this with $ adb tcpip <port-your-local-server>

Solution 13 - Django

What you need to do is to get your public PC IP and use it in your URL for example:, where 3000 is the port no.

Solution 14 - Django

I had the same issue in flutter with spring backend. Instead of using 'http://localhost:8080/'; in my requests, I changed this to ''; where '' is my Wi-Fi IPv4 address, and it worked.

(NOTE : I assume you are testing flutter in physical phone,and phone and computer are connected the same wi-fi.)

Solution 15 - Django

I know that the question is too old, But I will answer this because this may be helpful to someone who has this problem.

Without more details, I can't give a specific solution. But with following conditions can give a specific solution

  • I imagine that the API host was in local computer
  • I imagine that you use your emulator for running the app

The URL you tried with postman maybe something like this[port number]/register or http://localhost:[port number]/register. But this may not work with an emulator because it doesn't have access to that URL. To get access to the local host of your you need to find out the host address.

Follow these steps to get your host address.

  • Click on the three dots(More) in the android emulator
  • Setting -> Proxy
  • You can change your host address if you like by selecting `Manual proxy configuration

Then you can see your host name with the port number. Then replace your URL with those like

enter image description here

Solution 16 - Django

I had this same issue once, After going through some overly complicated stackoverflow answers and google search, finally i figure it out, In this case you are most likely to be using a android emulator, So just turn on the mobile data on the emulator then try it again, i'm sure that this time it will work.

Solution 17 - Django

final response = await
    headers: {"Authorization": apiKey},
    body: jsonEncode({
      "username": username,
      "password": password,

Even I had got a SocketException Error but I replaced my IP address and didn't mention any Port number and it worked for me, and if I mention the port number it would throw an error. Hoping this would work out.

I am using Flask for backend ,using blocs.

Solution 18 - Django

For mac users to check ip address

in terminal type: ipconfig getifaddr en0 and use that Ip address as below

import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:fluttertoast/fluttertoast.dart';

class AuthAction {
  static String BASE_URL = '';

  static Future<Null> signUpAction(
      firstName, lastName, email, password, userName) async {
    try {
      http.Response res = await Uri.parse(BASE_URL + 'signUp' ));

      if (res.statusCode == 200) {
    } catch (err) {

        // Fluttertoast.showToast(msg: 'err');

> Note: I did not touch the port on which my mongo-node server is running. Which is 27017

Solution 19 - Django

Try ths link delay the fuction and your will not get this error

Future.delayed(const Duration(milliseconds: 500), () {

It Work for me

Solution 20 - Django

If you are running on real phone, then you will get this error even if you add your localhost address to allowed host. For me, connecting my laptop to my phone's hotspot and running django server with laptop's ipv4 address (which you can find by using ipconfig command) by python runserver 192.168..:8000 i.e. your ipv4 address:port number, than you will be able to access django server using your phone's browser as well, now add this your ipv4 address to your allowed host. And, change your url from localhost or to your ipv4 address. I hope this resolves your issue.

Solution 21 - Django

Replace your URL with:
Uri.parse("YourURL").replace(host: "YourIPAddress");

Explanation: This error means your host-address isn't correct (as already in above answers pointed out). As you probably have a physical device it must access the emulator server you hooked up to your computer (aka your IP adress).

How to get my IP-Adress?

MAC: ifconfig | grep "inet " | grep -Fv | awk '{print $2}'

WINDOWS: netsh interface ip show address | findstr "IP Address"


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarnish RajputView Question on Stackoverflow
Solution 1 - DjangoRohan ThackerView Answer on Stackoverflow
Solution 2 - DjangospycbandaView Answer on Stackoverflow
Solution 3 - Djangotaranjeet singhView Answer on Stackoverflow
Solution 4 - DjangoRahman RezaeeView Answer on Stackoverflow
Solution 5 - DjangoTatenda ZifudziView Answer on Stackoverflow
Solution 6 - DjangoJoão Garcia de Lima NetoView Answer on Stackoverflow
Solution 7 - DjangoLuis De la CruzView Answer on Stackoverflow
Solution 8 - DjangoMartinho MussambaView Answer on Stackoverflow
Solution 9 - DjangoFelipe ThoméView Answer on Stackoverflow
Solution 10 - DjangoSergio MorstabiliniView Answer on Stackoverflow
Solution 11 - DjangosultanmyrzaView Answer on Stackoverflow
Solution 12 - Djangomurakami KauêView Answer on Stackoverflow
Solution 13 - DjangoMashood SiddiquieView Answer on Stackoverflow
Solution 14 - DjangoBurak Han GençmehmetoğluView Answer on Stackoverflow
Solution 15 - DjangoSayuru_SandaruView Answer on Stackoverflow
Solution 16 - DjangoAbhilash TUView Answer on Stackoverflow
Solution 17 - DjangoNithin MahendrenView Answer on Stackoverflow
Solution 18 - DjangoGurminder KalerView Answer on Stackoverflow
Solution 19 - DjangoUrvish JaniView Answer on Stackoverflow
Solution 20 - DjangoShiva GyawaliView Answer on Stackoverflow
Solution 21 - DjangoPaulView Answer on Stackoverflow