Change Computer IP address using JAVA

2020-03-24 08:21发布

I need to change computer IP address using java... I have tried this one but this doesnot 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);

标签: java ip lan
5条回答
劫难
2楼-- · 2020-03-24 08:37
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 returns are strange: java.lang.ProcessImpl@659e0bfd

no errors are found and my ip has been altered, but not in an expected way.

查看更多
Deceive 欺骗
3楼-- · 2020-03-24 08:38

I tested out the code you posted, and here is the error I got

Exception in thread "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 for fixing this, but I can say that looking at the code provided, the runtime seems to be useless unless used to form a loop, but since you didn't make the IP set as a randomly generated number, that would have no reason to be done.

查看更多
\"骚年 ilove
4楼-- · 2020-03-24 08:47

You (probably) need to correctly concatenate those key=value arguments - as written they'll be treated as separate arguments, i.e.

{..., "addr1=" + str1, "mask=" + str2 };
查看更多
该账号已被封号
5楼-- · 2020-03-24 08:52

make sure of the name of your interface

use netsh interface ipv4 show config in cmd to check the name of your connection

查看更多
兄弟一词,经得起流年.
6楼-- · 2020-03-24 08:53

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 the = are not separated by spaces. Also note the double quotation marks sourrounding Local Area Connection.

If this doesnt work either, try enclosing Local Area Connection in single quotation marks like this:

"name='Local Area Connection'"
查看更多
登录 后发表回答