JavaがIPを動的に切り替える方法(一)

3786 ワード

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 + "
"
); } 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; } }