Access Localhost Inside Android Emulator
Greetings, friends! When developing a website, it's sometimes necessary to check how it behaves in an Android device. There could be bugs that only exist in browsers on Android, or you may want to see what the user experience (UX) is like on a phone. If you don't happen to have a real Android device on hand, you can always run an Android emulator using Android Studio as discussed in my previous article. Let's see how we can access localhost inside the Android emulator to help with development!
Let's run a web server using a simple Node.js script:
const http = require('http');
let app = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1 style="font-size: 5rem;">Hello World</h1>');
});
app.listen(3000);
console.log('Node server listening on port 3000');
Now, let's open up the Android Emulator. If you're using Android Studio to run the emulator, then localhost of your host computer will be mapped to the IP address, 10.0.2.2
, inside the emulator. If you're using other programs to run the emulator, then you may need to consult the documentation associated with those programs. Since we chose to run the Node.js server on port 3000, we need to navigate to 10.0.2.2:3000
inside the Android Emulator.
Ta-da! 🎉
Each instance of the Android emulator runs behind a virtual router/firewall. You can find a list of IP addresses used in the network address space here. Among these IP addresses, you will find a special alias to your host computer's loopback interface (aka localhost). This alias is 10.0.2.2
, the same IP address we used to access localhost of our host computer inside the Android emulator.
Conclusion
This is a quick and easy way to access a server running locally on your host computer from the Android emulator. Hope you found it useful. Please check out the resources below to learn more about the Android emulator.