创建端口转发
private static bool CreateChannle(out string msg)
{
msg = "";
Random random = new Random();
int port = 0;
int times = 0;
do
{
port = random.Next(1000, 50000);
times++;
} while (!CheckPortAvailable(port) && times < 10);
if (times >= 10)
{
msg = "无可用端口";
return false;
}
string cmd = string.Format("netsh interface portproxy add v4tov4 listenport={0} connectaddress=dtdl.channel.lebaoba.com connectport=11808",port);
string r = ExecuteCmd(cmd);
string result = r.Substring(r.IndexOf("exit") + 4);
if (result.Replace("\r\n", "").Length == 0)
{
msg = "127.0.0.1:" + port.ToString();
return true;
}
else
{
msg = result;
return false;
}
}
检查端口是否可用
private static bool CheckPortAvailable(int port)
{
string cmd = string.Format("netstat -ano | findstr \"{0}\"", port);
string r = ExecuteCmd(cmd);
string result = r.Substring(r.IndexOf("exit") + 4);
if (result.Replace("\r\n", "").Length == 0)
{
return true;
}
else
{
return false;
}
}
查看创建的所有转发通道
private static List<string> SearchChannle()
{
List<string> list = new List<string>();
string cmd = "netsh interface portproxy show v4tov4";
string r = ExecuteCmd(cmd);
r = r.Substring(r.IndexOf("exit") + 4);
string[] lines = r.Replace("\r\n", "^").Split('^');
for (int i = 6; i < lines.Length; i++)
{
if (!string.IsNullOrEmpty(lines[i]))
{
string channelString = "";
string[] temp = lines[i].Split(' ');
foreach (var item in temp)
{
if (!string.IsNullOrEmpty(item))
{
channelString += item + "|";
}
}
list.Add(channelString);
}
}
return list;
}
删除一条转发通道
private static void DeleteChannel(string ip,string port)
{
string cmd = "";
if (ip == "*")
{
cmd = string.Format("netsh interface portproxy delete v4tov4 listenaddress={0} listenport={1}", ip, port);
}
else
{
cmd = string.Format("netsh interface portproxy delete v4tov4 listenport={0}", port);
}
ExecuteCmd(cmd);
}
删除所有转发通道
private static void DeleteAllChannels()
{
List<string> channcelList = SearchChannle();
foreach (var channcel in channcelList)
{
DeleteChannel(channcel.Split('|')[0], channcel.Split('|')[1]);
}
}
执行cmd指令的方法
private static string ExecuteCmd(string strInput)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine(strInput + "&exit");
p.StandardInput.AutoFlush = true;
string strOuput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
return strOuput;
}