Changing the IP address of a computer using JAVA

I need to change the IP address of a computer using java ... I tried this one but it doesn't work ...

    String str1="192.168.0.201"; 
    String str2="255.255.255.0";
    String[] command1 = { "netsh", "interface", "ip", "set", "address",
    "name=", "Local Area Connection" ,"source=static", "addr=",str1,
    "mask=", str2};
    Process pp = java.lang.Runtime.getRuntime().exec(command1);

      

+3


source to share


5 answers


You (maybe) need to concatenate those arguments correctly key=value

- as written, they will be treated as separate arguments, i.e.



{..., "addr1=" + str1, "mask=" + str2 };

      

+2


source


Have you tried this?

String[] command1 = { "netsh", "interface", "ip", "set", "address",
"name=\"Local Area Connection\"" ,"source=static", "addr="+str1,
"mask="+str2};

      

Note that now the arguments after = are not separated by spaces. Also notice the double quotes surrounding the local connection.



If that doesn't work, try enabling local connection in single quotes like this:

"name='Local Area Connection'"

      

+1


source


I checked the code you posted and here is the error I got

Exception on stream "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type IOException

at DaysinaMonth.main(DaysinaMonth.java:9)

      

the error was found on this line:

Process pp = java.lang.Runtime.getRuntime().exec(command1);

      

I have no suggestions to fix this, but I can say that by looking at the provided code, the runtime seems to be useless unless it is used to form a loop, but since you didn’t make the IP set as a randomly generated number, that wasn’t would be a reason for this.

0


source


public class DaysinaMonth {
    public static void main(String[] args) throws Throwable{
        String str1="192.168.0.201"; 
        String str2="255.255.255.0";
        String[] command1 = { "netsh", "interface", "ip", "set", "address",
        "name=", "Local Area Connection" ,"source=static", "addr=",str1,
        "mask=", str2};
        Process pp = java.lang.Runtime.getRuntime().exec(command1);
        System.out.print( pp);
    }
}

      

This seems to work, but the results are strange: java.lang.ProcessImpl@659e0bfd

no errors were found and my ip was changed, but not in the expected way.

0


source


make sure the name of your interface is correct

use netsh interface ipv4 show config

in cmd to check your connection name

0


source







All Articles