您的位置:首页 > 编程语言 > Java开发

Java实现动态切换IP的方法(一)

2017-07-29 10:12 323 查看
通过调用Windows的rasdial命令来实现ip的切换。

下面我们来看下rasdial的语法:

拨号语法:

rasdial 连接名称(可随意命名) ‘宽带账号’ ‘宽带密码’

断开语法:

rasdial 连接名称 /disconnect

Java代码:

package com.koy.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
* Created by koy.
*/
public class IpUtils {
/**
* 调用cmd命令
*
* @param cmd windows命令
* @return 执行结果
* @throws Exception
*/
public static String executeCmd (String cmd) throws Exception {
Process process = Runtime.getRuntime ().exec ("cmd /c " + cmd);
StringBuilder executeResult = new StringBuilder ();
BufferedReader br = new BufferedReader (new InputStreamReader (process.getInputStream ()));
String line;
while ((line = br.readLine ()) != null) {
executeResult.append (line + "\n");
}
return executeResult.toString ();
}

/**
* 连接ADSL
*
* @param adslTitle 名称
* @param adslName  账号名称
* @param adlsPwd   密码
* @return 是否成功
* @throws Exception
*/
public static boolean connAdsl (String adslTitle, String adslName, String adlsPwd) throws Exception {
String adslCmd = "rasdial " + adslTitle + " " + adslName + " " + adlsPwd;

return executeCmd (adslCmd).indexOf ("已连接") > 0 ? true : false;
}

/**
* 断开ADSL
*
* @param adslTitle 名称
* @return 是否成功
* @throws Exception
*/
public static boolean cutAdsl (String adslTitle) throws Exception {
String adslCmd = "rasdial " + adslTitle + " /disconnect";

return executeCmd (adslCmd).indexOf ("没有连接") != -1 ? false : true;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java ip