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

通过调用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;
    }

}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值