利用C#代碼創(chuàng)建、查看、刪除端口轉(zhuǎn)發(fā)
當(dāng)前位置:點(diǎn)晴教程→知識管理交流
→『 技術(shù)文檔交流 』
創(chuàng)建端口轉(zhuǎn)發(fā)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;
}
} 看創(chuàng)建的所有轉(zhuǎn)發(fā)通道 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;
} 刪除一條轉(zhuǎn)發(fā)通道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);
} 刪除所有轉(zhuǎn)發(fā)通道private static void DeleteAllChannels()
{
List<string> channcelList = SearchChannle();
foreach (var channcel in channcelList)
{
DeleteChannel(channcel.Split(''|'')[0], channcel.Split(''|'')[1]);
}
} 執(zhí)行cmd指令的方法private static string ExecuteCmd(string strInput)
{
Process p = new Process();
//設(shè)置要啟動的應(yīng)用程序
p.StartInfo.FileName = "cmd.exe";
//是否使用操作系統(tǒng)shell啟動
p.StartInfo.UseShellExecute = false;
// 接受來自調(diào)用程序的輸入信息
p.StartInfo.RedirectStandardInput = true;
//輸出信息
p.StartInfo.RedirectStandardOutput = true;
// 輸出錯誤
p.StartInfo.RedirectStandardError = true;
//不顯示程序窗口
p.StartInfo.CreateNoWindow = true;
//啟動程序
p.Start();
//向cmd窗口發(fā)送輸入信息
p.StandardInput.WriteLine(strInput + "&exit");
p.StandardInput.AutoFlush = true;
//獲取輸出信息
string strOuput = p.StandardOutput.ReadToEnd();
//等待程序執(zhí)行完退出進(jìn)程
p.WaitForExit();
p.Close();
return strOuput;
}
該文章在 2021/2/2 15:24:41 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |