---
title: "【转载】java实现动态切换上网IP (ADSL拨号上网"
author: "narutolby"
date: "2013-11-15T14:08:28Z"
tags: []
categories: ["编程语言"]
slug: "java-ip-adsl"
draft: false
lastmod: "2013-11-15T14:08:28Z"
id: 1975149
url: "https://narutolby.iteye.com/blog/1975149"
---

转载：[http://sesame.iteye.com/blog/434088](http://sesame.iteye.com/blog/434088)

 

动态切换IP的实现主是也由Windows的rasdial命令提供的，其实不是java的功劳，java只是调用一下bat脚本而已：

rasdial命令：

 

拨号

Java代码  [![收藏代码](http://sesame.iteye.com/images/icon_star.png)]()

1. 语法： rasdial  连接名称 username password
2. 实例： rasdial 我的宽带 hzhz1234567890 dfdfdfdfdf

断网

Java代码  [![收藏代码](http://sesame.iteye.com/images/icon_star.png)]()

1. 语法：rasdial  连接名称 /disconnect
2. 实例： rasdial 宽带  /disconnect

 

java程序调用rasdial命令：

Java代码  [![收藏代码](http://sesame.iteye.com/images/icon_star.png)]()

01. package com.sesame.network;
02. import java.io.BufferedReader;
03. import java.io.InputStreamReader;
04. public class ConnectNetWork {
05. /\**
06. * 执行CMD命令,并返回String字符串
07. \*/
08. public static String executeCmd(String strCmd) throws Exception {
09. Process p = Runtime.getRuntime().exec("cmd /c " + strCmd);
10. StringBuilder sbCmd = new StringBuilder();
11. BufferedReader br = new BufferedReader(new InputStreamReader(p
12. .getInputStream()));
13. String line;
14. while ((line = br.readLine()) != null) {
15. sbCmd.append(line + "\\n");
16. }
17. return sbCmd.toString();
18. }
19. /\**
20. * 连接ADSL
21. \*/
22. public static boolean connAdsl(String adslTitle, String adslName, String adslPass) throws Exception {
23. System.out.println("正在建立连接.");
24. String adslCmd = "rasdial " + adslTitle + " " + adslName + " "
25. + adslPass;
26. String tempCmd = executeCmd(adslCmd);
27. // 判断是否连接成功
28. if (tempCmd.indexOf("已连接") &gt; 0) {
29. System.out.println("已成功建立连接.");
30. return true;
31. } else {
32. System.err.println(tempCmd);
33. System.err.println("建立连接失败");
34. return false;
35. }
36. }
37. /\**
38. * 断开ADSL
39. \*/
40. public static boolean cutAdsl(String adslTitle) throws Exception {
41. String cutAdsl = "rasdial " + adslTitle + " /disconnect";
42. String result = executeCmd(cutAdsl);
43. if (result.indexOf("没有连接")!=-1){
44. System.err.println(adslTitle + "连接不存在!");
45. return false;
46. } else {
47. System.out.println("连接已断开");
48. return true;
49. }
50. }
51. public static void main(String\[] args) throws Exception {
52. connAdsl("宽带","hzhz\*\*\*\*\*\*\*\*\*\*","\*\*\*\*\*\*");
53. Thread.sleep(1000);
54. cutAdsl("宽带");
55. Thread.sleep(1000);
56. //再连，分配一个新的IP
57. connAdsl("宽带","hzhz\*\*\*\*\*\*\*\*\*\*","\*\*\*\*\*\*");
58. }
59. }

 

执行结果：

Java代码  [![收藏代码](http://sesame.iteye.com/images/icon_star.png)]()

1. 正在建立连接.
2. 已成功建立连接.
3. 连接已断开
4. 正在建立连接.
5. 已成功建立连接.