Reputation: 27221
What is 'localhost' address for Android device?
I'm testing a program using client and server at the same app.
neither SERVER_IP ="http://localhost"
nor "http://127.0.0.1"
works for
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
it gives:
Unable to resolve host
"http://localhost"
: No address associated with hostname android
What is the best way to use localhost?
UPDATE
Thanks to all comments: "http://localhost"
is incorrecct. Right is "localhost"
or "127.0.0.1"
or "127.0.0.2"
, etc. But I hope the best solution is the marked answer.
Upvotes: 2
Views: 4053
Reputation: 3000
Sockets communicate over TCP, which is a lower level protocol than HTTP. When you are identifying a server address for socket communication, use the bare name of the server (for example, "localhost") or a dotted quad (for example "192.168.0.100").
Don't include http:// or any other scheme.
If I understand the question correctly and the goal is to open a socket from and to the same machine (the phone), you can just use
InetAddress serverAddr = InetAddress.getByName(null);
to get the "loopback" interface, which is equivalent to using localhost.
Upvotes: 3