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);
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 };
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'"
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.
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.
make sure the name of your interface is correct
use netsh interface ipv4 show config
in cmd to check your connection name