Why can't my dart shelf webservice be bound to 0.0.0.0?

250 Views Asked by At

I've been trying to change the hostname of this HTTPServer in order to access it from any machine on the network, however the site is still only accessible through localhost. I have tried parsing the "0.0.0.0" hostname string into an InternetAddress however this didn't work either.

import 'package:shelf_router/shelf_router.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'dart:convert';

void main(List<String> arguments) async {
  final app = Router();
  const _hostname = "0.0.0.0";
  const _port = 8080;

  app.get('/', (Request request) {
    var queryParameters = request.requestedUri.queryParameters;
    var error = false;
    var resultMessage = "";
    int x, y, z;

    print(request);

    if (queryParameters["x"] != null)
      try {
        x = int.parse(queryParameters["x"]);
      } on FormatException {
        resultMessage =
            resultMessage + "Please provide a numerical value for x.";
        error = true;
      }
    else {
      resultMessage = resultMessage + "Please provide a value for x.";
      error = true;
    }

    if (queryParameters["y"] != null)
      try {
        y = int.parse(queryParameters["y"]);
      } on FormatException {
        resultMessage =
            resultMessage + "Please provide a numerical value for y.";
        error = true;
      }
    else {
      resultMessage = resultMessage + "Please provide a value for y.";
      error = true;
    }

    if (error) {
      var test = {"error": true, "string": resultMessage, "answer": 0};
      //var resp = new Response(400);
      return Response.ok(json.encode(test));
    } else {
      z = (x ~/ y);
    }

    var test = {"error": false, "string": "${x} / ${y} = ${z}", "answer": 0};
    return Response.ok(
      json.encode(test),
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
    );
  });

  await io.serve(app.handler, _hostname, _port);
}

Please excuse the juvenility of the code, as this is my first time using dart.

EDIT: More info - IDE is VS Code, Kali linux in command line to execute. My plan is to containerise and deploy this onto a kubernetes cluster, just FYI.

0

There are 0 best solutions below