Marcello Davi
Marcello Davi

Reputation: 433

Can't connect to Android server using hostname

i'm trying to make a Java application that connects to an Android application.

Both my pc and my phone are connected to the same network.

This is the Java client wich runs on my pc:

client = new Socket("muffin", port);

System.out.println("Connected");

output = new ObjectOutputStream(client.getOutputStream());
output.flush();
input = new ObjectInputStream(client.getInputStream());

System.out.println("Streams ready");

And this is the Android application wich works as the server:

server = new ServerSocket(port);
socket = server.accept();

Log.i("Server", "Connected");

output = new ObjectOutputStream(socket.getOutputStream());
output.flush();
input = new ObjectInputStream(socket.getInputStream());

In the manifest i added the permissions:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

As you can see i'm trying to connect from my pc to the android server by using its hostname (i changed my android hostname to "muffin"), but it doesn't connect and it throws an exception:

java.net.UnknownHostException: muffin

If instead of the hostname i use the ip address, it works without problems. It looks like it cannot find a device on LAN called "muffin", but you can see from this screenshot of my modem page that the name is right:

My modem page that shows connected client

That said, i tryed to use the android application as the client and the java program as the server, but it looks like android has some problems because it didn't connect to my pc even by using the ip address instead of the hostname.

Do you have any idea on how to fix this problem?

Thanks in advance and sorry for my english, it's not my mother tongue.

Upvotes: 1

Views: 966

Answers (2)

Marcello Davi
Marcello Davi

Reputation: 433

I solved the problem, i've had to allow the traffic on the specific port through the windows firewall.

Now i can connect to the android application using its hostname.

Upvotes: 1

Cukic0d
Cukic0d

Reputation: 5411

You can't do:

new Socket("muffin", port);

There is a difference between Hostname, and Host, so:

java.net.UnknownHostException: muffin

means that the host "muffin" doesn't exist, and that's true: the only existing host is 192.168.1.105, who has a hostname who is "muffin".

So you should have done:

new Socket("192.168.1.105", port);

It is not possible to get a host from it's hostname : so if it is the only way for you to do it, you will have to do a huge scan of all the local network, and then see which host that is connected has the good hostname. As this method is much much harder, i realy recommand you to find another way to do it :)

Upvotes: 0

Related Questions