一、端口與網絡通信
端口號用於在網絡通信時標識通信端點,是一種抽象的概念。在Windows中,共有65,535個端口號,其中從0至1023為系統保留端口,被系統或常用應用程序佔用,一般要求管理員權限才能綁定。
使用網絡通信的程序,需要將數據發送給特定的端口,接收方也是通過綁定監聽端口被動接收數據,這些端口可能會被惡意程序濫用,導致佔用端口的現象。
二、如何查看端口佔用情況
在Windows操作系統中, Task Manager是最常規的查看端口佔用情況的工具。可以進入‘進程’標籤頁,點擊‘打開資源監視器’,在資源監視器的‘網絡’標籤頁中查看網絡連接情況,包括TCP和UDP連接,以及對應端口及佔用程序。
//獲取TCP端口佔用情況示例代碼
var tcpConnections = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections();
foreach (TcpConnectionInformation tcpInfo in tcpConnections) {
Console.WriteLine("Local Address: {0}:{1}\tRemote Address: {2}:{3}\tState: {4}",
tcpInfo.LocalEndPoint.Address, tcpInfo.LocalEndPoint.Port,
tcpInfo.RemoteEndPoint.Address, tcpInfo.RemoteEndPoint.Port, tcpInfo.State);
}
//獲取UDP端口佔用情況示例代碼
var udpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
foreach (IPEndPoint endPoint in udpListeners) {
Console.WriteLine("Local Address: {0}:{1}", endPoint.Address, endPoint.Port);
}
三、如何釋放端口佔用
當端口被非正常佔用時,會導致正常的網絡通信受到阻礙,需要釋放該端口的佔用。常規的做法是關閉對應的程序或服務,但某些程序可能存在無法關閉的情況,這時可以使用一些工具進行強制終止佔用端口的程序。
在Windows中,命令行工具netstat可以查詢與TCP/IP連接相關的信息。使用netstat -a命令可以查詢所有經過驗證的TCP和UDP端口,包括監聽狀態和正在連接的端口。使用netstat -o命令可以查看佔用端口的PID,根據PID可以重啟、結束佔用的進程。Windows 10以上版本可以使用’資源監視器’的網絡標籤頁,右鍵要結束的進程名,選擇‘終止進程’。
//釋放當前已知端口號的佔用示例代碼
var processList = Process.GetProcesses();
foreach (Process process in processList) {
try {
var portList = IPGlobalProperties.GetIPGlobalProperties()
.GetActiveTcpListeners().Select(p => p.Port)
.Union(IPGlobalProperties.GetIPGlobalProperties()
.GetActiveUdpListeners().Select(p => p.Port)).ToList();
foreach (var port in portList) {
var processName = process.ProcessName;
var portUsed = process.GetNetStat(port, ProtocolType.Tcp).Concat(
process.GetNetStat(port, ProtocolType.Udp)).ToList();
if (portUsed.Any()) {
Console.WriteLine("Killing the process: {0}, which is listening on the port {1}",
processName, port);
process.Kill();
}
}
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
四、如何防止非法佔用端口現象
為防止非法佔用端口,我們可以在編寫程序時考慮以下幾個方面:
- 選擇閑置端口,不建議使用系統常用端口;
- 確保不同程序之間不會佔用同一端口;
- 關閉不必要的監聽服務;
- 正確處理異常情況,釋放佔用的端口;
- 使用防火牆等安全工具進行保護。
原創文章,作者:FZUTL,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/335139.html
微信掃一掃
支付寶掃一掃