envoy / Embassy

Super lightweight async HTTP server library in pure Swift runs in iOS / MacOS / Linux

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can't access HTTP server from another device within network

DennisWeirauch opened this issue · comments

Hi,
I am trying to figure out how to send requests to the server from other devices within the network. When I embed the example in my iOS App, open up Safari and type in my iPhone's IP, I get a correct response from the server.
But how can I access the HTTP server from another device? Do I have to get any permissions to access the device remotely?
I also tried a similar functionality with IBM's Kitura, where this functionality is working. But as I prefer this framework, I would like to find a solution with Embassy.

Hi @DennisHirschgaenger,

For security reason, Embassy by default is using ::1 as the binding interface for the HTTP TCP socket, which is the localhost (or 127.0.0.1 in IPv4). As you can see the default interface here

https://github.com/envoy/Embassy/blob/master/Sources/DefaultHTTPServer.swift#L28

As a result, it only allows connection from localhost (127.0.0.1)

To make it to public network, you can bind it to ::, which is 0.0.0.0 in IPv4. (you can also bind it to other interface if you want).

So, given the example from README, to server request from all network will be

let loop = try! SelectorEventLoop(selector: try! KqueueSelector())
let server = DefaultHTTPServer(eventLoop: loop, interface: "::", port: 8080) {
    (
        environ: [String: Any],
        startResponse: ((String, [(String, String)]) -> Void),
        sendBody: ((Data) -> Void)
    ) in
    // Start HTTP response
    startResponse("200 OK", [])
    let pathInfo = environ["PATH_INFO"]! as! String
    sendBody(Data("the path you're visiting is \(pathInfo.debugDescription)".utf8))
    // send EOF
    sendBody(Data())
}

// Start HTTP server to listen on the port
try! server.start()

// Run event loop
loop.runForever()

Please notice that we pass interface: "::" to the DefaultHTTPServer here, to make it binds to the all network interface. You can also bind it to arbitrary interface other than :: if you want, as long as you only want your iPhone to bind on that specific interface. And remember, by doing so, all peers in the same network with the iPhone should be able to access, please be sure this is what you expected.

Thank you so much. Now it works perfectly