How can I access my localhost from my Android device?

前端 未结 30 2270
面向向阳花
面向向阳花 2020-11-21 05:53

I\'m able to access my laptop web server using the Android emulator, I\'m using 10.0.2.2:portno works well.

But when I connect my real Android phone, th

30条回答
  •  既然无缘
    2020-11-21 06:44

    With the simple solution (just access laptop_ip_addr:port from mobile device, when mobile and laptop are on the same WiFi), I get a ERR_CONNECTION_REFUSED error. That is, my MacBook seems to refuse the connection attempt from my mobile.


    ADB Reverse Socket (Android only)

    This solution works for me (tested with a MacBook):

    1. Connect Android mobile device with USB cable to laptop
    2. Enable USB Debugging on mobile device
    3. On laptop, run adb reverse tcp:4000 tcp:4000
      • Use your custom port number instead of 4000
    4. Now, on the mobile device, you can navigate to http://localhost:4000/, and it will actually connect to the laptop, not the mobile device

    See instructions here.

    The downside is that this works only with a single mobile device at a time. If you want access with another mobile device, you have to first disconnect the first one (disable USB Debugging), connect the new one (enable USB Debugging), and run adb reverse tcp:4000 tcp:4000 again.


    ngrok (works with all devices)

    Another solution that should always work is ngrok (as mentioned in other answers). It works over the Internet, and not the local network.

    It's extremely easy to use:

    brew cask install ngrok
    ngrok http 4000
    

    This outputs, among some other information, a line like

    Forwarding                    http://4cc5ac02.ngrok.io -> localhost:4000
    

    Now, you can navigate to http://4cc5ac02.ngrok.io on any device that is connected to the Internet, and this URL redirects to localhost:4000 of your laptop.

    Note that as long as the ngrok command is running (until you hit Ctrl-C), your project is publicly served. Everybody who has the URL can see it.

提交回复
热议问题