Vyacheslav
Vyacheslav

Reputation: 27221

What is localhost for Android?

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

Answers (2)

x-code
x-code

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

RyPope
RyPope

Reputation: 2725

According to this answer, you can simply use your local IP to act as localhost. You can find it by using ipconfig on Windows or ifconfig on linux.

Apparently you can also substitute 10.0.2.2

Upvotes: 1

Related Questions