How do I pass the IP address typed in the command-line to the client socket constructor in Java?

StackOverflow https://stackoverflow.com/questions/22548933

  •  18-06-2023
  •  | 
  •  

Frage

I do not know how to read the IP address and use it when I am initializing a socket.

How do I do that?

Here is my socket code on the client side, if needed:

 Socket socket;
 socket = new Socket("localhost", 16789);
War es hilfreich?

Lösung

public class Echo {
    public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
            Socket socket;
            socket = new Socket(s, 16789);
        }
    }
}

Note that this code would parse multiple command line arguments. If you only have one you can use args[0] and get rid of the for loop.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top