How to connect to local server without hardcoding the IP address

Viewed 31

I have a local console-based server that I would like to connect to with an android app (emulator) both running on the same computer.

Server code.

public void startServer() {

    serverSocket = new ServerSocket(5050);
    System.out.printf("Server started on ip= %s port= 5050\n", InetAddress.getLocalHost().getHostAddress());
    while (true) {  
        Socket clientSocket = serverSocket.accept();
        System.out.println("Accepted");
    }
}
   

Client

Socket connection = new Socket("192.168.92.11", 5050);

But the problem I do not want to hardcode the IP address in case, I want the app to automatically detect the local IP and connect to the server.

I tried this below but the app keeps crashing

 Socket connection = new Socket(InetAddress.getLocalHost().getHostAddress(), 5050);

Is there another way I can achieve this?

0 Answers
Related