1

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?

Laurel
  • 5,965
  • 14
  • 31
  • 57
Rising Sun
  • 11
  • 2
  • How about using `"localhost"` instead of IP like `Socket connection = new Socket("localhost", 5050);`? – Pshemo Sep 20 '22 at 20:31
  • "..but the app keeps crushing" usually while problem occurs there is some error message or even entry to log file. Could you include it in your question? – Pshemo Sep 20 '22 at 20:34
  • Does this answer your question? [java InetAddress.getLocalHost(); returns 127.0.0.1 ... how to get REAL IP?](https://stackoverflow.com/questions/2381316/java-inetaddress-getlocalhost-returns-127-0-0-1-how-to-get-real-ip) – Steffen Sep 20 '22 at 20:40
  • new Socket("10.0.2.2", 5050); – blackapps Sep 20 '22 at 20:50

0 Answers0