I have been connecting two PCs via Wi-Fi and I'm using IP address to do this like the example below:
String ipAddress = "192.168.X.X";
Socket socket = new Socket(ipAddress, 8888);
My IP address regularly change so this is a hassle for me and I want to use the computer's name instead of this. How is this possible?
EDIT:
From the replies below, I was able to do it this way on two PCs:
String ipAddress = "somename";
Socket socket = new Socket(InetAddress.getByName(ipAddress), 12345);
and this
String ipAddress = "somename";
Socket socket = new Socket(ipAddress, 8888);
but when I apply it on my Android app, it doesn't work. Is there a special way to do it in Android?
Instead of an IP adress you can also use a hostname. For example if your server has hostname "foo.bar.com" you can use
Socket socket = new Socket("foo.bar.com", port);
In your local network you should be able to use the hostnames of the local pc's. I have just written a small example that sucessfully connects to my printserver:
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketTester {
/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
//Create socket connection
try{
Socket socket = new Socket("printserver", 23);
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
try{
while(in.read()!=-1){
String line = in.readLine();
System.out.println("Text received: " + line);
}
} catch (IOException e){
System.out.println("Read failed");
System.exit(1);
}
} catch (UnknownHostException e) {
System.out.println("Unknown host: kq6py");
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.