C# socket nat 映射 網絡 代理 轉發

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;


namespace portmap_net
{
? ? /// <summary>
? ? /// 映射器實例狀態
? ? /// </summary>
? ? sealed internal class state
? ? {


? ? ? ? #region Fields (5)


? ? ? ? public int _connect_cnt;
? ? ? ? public string _point_in;
? ? ? ? public string _point_out;
? ? ? ? public const string _print_head = "輸入IP ? ? ? ? ? ? ?輸出IP ? ? ? ? ? ? ?狀態 ? ?連接數 ? ?接收/發送";
? ? ? ? public bool _running;
? ? ? ? public long _bytes_send;
? ? ? ? public long _bytes_recv;


? ? ? ? #endregion Fields


? ? ? ? #region Constructors (1)


? ? ? ? public state(string point_in, string point_out, bool running, int connect_cnt, int bytes_send, int bytes_recv)
? ? ? ? {
? ? ? ? ? ? _point_in = point_in;
? ? ? ? ? ? _point_out = point_out;
? ? ? ? ? ? _running = running;
? ? ? ? ? ? _connect_cnt = connect_cnt;
? ? ? ? ? ? _bytes_recv = bytes_recv;
? ? ? ? ? ? _bytes_send = bytes_send;
? ? ? ? }


? ? ? ? #endregion Constructors


? ? ? ? #region Methods (1)


? ? ? ? // Public Methods (1)


? ? ? ? public override string ToString()
? ? ? ? {
? ? ? ? ? ? return string.Format("{0}{1}{2}{3}{4}", _point_in.PadRight(20, ' '), _point_out.PadRight(20, ' '), (_running ? "運行中 ?" : "啟動失敗"), _connect_cnt.ToString().PadRight(10, ' '), Math.Round((double)_bytes_recv / 1024) + "k/" + Math.Round((double)_bytes_send / 1024) + "k");
? ? ? ? }


? ? ? ? #endregion Methods
? ? }


? ? /// <summary>
? ? /// 映射器線程所需數據
? ? /// </summary>
? ? internal struct work_item
? ? {


? ? ? ? #region Data Members (4)


? ? ? ? public int _id;
? ? ? ? public EndPoint _ip_in;
? ? ? ? public string _ip_out_host;
? ? ? ? public ushort _ip_out_port;


? ? ? ? #endregion Data Members
? ? }


? ? /// <summary>
? ? /// 主程序
? ? /// </summary>
? ? sealed internal class program
? ? {


? ? ? ? #region Fields (4)


? ? ? ? private static StringBuilder _console_buf = new StringBuilder();
? ? ? ? /// <summary>
? ? ? ? /// 程序已啟動的所有映射器實例, key=id
? ? ? ? /// </summary>
? ? ? ? private static readonly Dictionary<int, state> _state_dic = new Dictionary<int, state>();
? ? ? ? #endregion Fields


? ? ? ? #region Methods (8)


? ? ? ? // Private Methods (8)


? ? ? ? private static void Main()
? ? ? ? {
? ? ? ? ? ? //映射器參數
? ? ? ? ? ? List<work_item> maps_list = new List<work_item>{
? ? ? ? ? ? ? ? new work_item{_id = 1, _ip_in = new IPEndPoint(IPAddress.Any,2012), _ip_out_host="123.321.18.38", _ip_out_port = 3389 },
? ? ? ? ? ? ? ? new work_item{_id = 2, _ip_in = new IPEndPoint(IPAddress.Any,2013), _ip_out_host="www.baidu.com", _ip_out_port = 80 }
? ? ? ? ? ? };


? ? ? ? ? ? //啟動映射器
? ? ? ? ? ? foreach (var map_item in maps_list)
? ? ? ? ? ? ? ? map_start(map_item);


? ? ? ? ? ? Console.CursorVisible = false;
? ? ? ? ? ? while (true)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? //每2秒刷新屏幕, 顯示映射器狀態
? ? ? ? ? ? ? ? show_state();
? ? ? ? ? ? ? ? Thread.Sleep(2000);
? ? ? ? ? ? }
? ? ? ? }


? ? ? ? /// <summary>
? ? ? ? /// 啟動映射器
? ? ? ? /// </summary>
? ? ? ? /// <param name="work"></param>
? ? ? ? private static void map_start(work_item work)
? ? ? ? {
? ? ? ? ? ? Socket sock_svr = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
? ? ? ? ? ? bool start_error = false;
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? sock_svr.Bind(work._ip_in);//綁定本機ip
? ? ? ? ? ? ? ? sock_svr.Listen(10);
? ? ? ? ? ? ? ? sock_svr.BeginAccept(on_local_connected, new object[] { sock_svr, work });//接受connect
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? start_error = true;
? ? ? ? ? ? }
? ? ? ? ? ? finally
? ? ? ? ? ? {
? ? ? ? ? ? ? ? _state_dic.Add(work._id, new state(work._ip_in.ToString(), work._ip_out_host + ":" + work._ip_out_port, !start_error, 0, 0, 0));
? ? ? ? ? ? }
? ? ? ? }


? ? ? ? /// <summary>
? ? ? ? /// 收到connect
? ? ? ? /// </summary>
? ? ? ? /// <param name="ar"></param>
? ? ? ? private static void on_local_connected(IAsyncResult ar)
? ? ? ? {
? ? ? ? ? ? object[] ar_arr = ar.AsyncState as object[];
? ? ? ? ? ? Socket sock_svr = ar_arr[0] as Socket;
? ? ? ? ? ? work_item work = (work_item)ar_arr[1];


? ? ? ? ? ? ++_state_dic[work._id]._connect_cnt;
? ? ? ? ? ? Socket sock_cli = sock_svr.EndAccept(ar);
? ? ? ? ? ? sock_svr.BeginAccept(on_local_connected, ar.AsyncState);
? ? ? ? ? ? Socket sock_cli_remote = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? sock_cli_remote.Connect(work._ip_out_host, work._ip_out_port);
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? try
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? sock_cli.Shutdown(SocketShutdown.Both);
? ? ? ? ? ? ? ? ? ? sock_cli_remote.Shutdown(SocketShutdown.Both);
? ? ? ? ? ? ? ? ? ? sock_cli.Close();
? ? ? ? ? ? ? ? ? ? sock_cli_remote.Close();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? catch (Exception)
? ? ? ? ? ? ? ? { }
? ? ? ? ? ? ? ? --_state_dic[work._id]._connect_cnt;
? ? ? ? ? ? ? ? return;
? ? ? ? ? ? }
? ? ? ? ? ? //線程: 接受本地數據 轉發至遠程
? ? ? ? ? ? Thread t_send = new Thread(recv_and_send_caller) { IsBackground = true };
? ? ? ? ? ? //線程: 接受遠程數據 轉發至本地connect 端
? ? ? ? ? ? Thread t_recv = new Thread(recv_and_send_caller) { IsBackground = true };
? ? ? ? ? ? t_send.Start(new object[] { sock_cli, sock_cli_remote, work._id, true });
? ? ? ? ? ? t_recv.Start(new object[] { sock_cli_remote, sock_cli, work._id, false });
? ? ? ? ? ? //線程同步
? ? ? ? ? ? t_send.Join();
? ? ? ? ? ? t_recv.Join();
? ? ? ? ? ? //已斷開, 連接數-1
? ? ? ? ? ? --_state_dic[work._id]._connect_cnt;
? ? ? ? }


? ? ? ? /// <summary>
? ? ? ? /// 數據轉發
? ? ? ? /// </summary>
? ? ? ? /// <param name="from_sock"></param>
? ? ? ? /// <param name="to_sock"></param>
? ? ? ? /// <param name="send_complete"></param>
? ? ? ? private static void recv_and_send(Socket from_sock, Socket to_sock, Action<int> send_complete)
? ? ? ? {
? ? ? ? ? ? byte[] recv_buf = new byte[4096];
? ? ? ? ? ? int recv_len;
? ? ? ? ? ? while ((recv_len = from_sock.Receive(recv_buf)) > 0)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? to_sock.Send(recv_buf, 0, recv_len, SocketFlags.None);
? ? ? ? ? ? ? ? send_complete(recv_len);
? ? ? ? ? ? }
? ? ? ? }


? ? ? ? private static void recv_and_send_caller(object thread_param)
? ? ? ? {
? ? ? ? ? ? object[] param_arr = thread_param as object[];
? ? ? ? ? ? Socket sock1 = param_arr[0] as Socket;
? ? ? ? ? ? Socket sock2 = param_arr[1] as Socket;
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? recv_and_send(sock1, sock2, bytes =>
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? state stat = _state_dic[(int)param_arr[2]];
? ? ? ? ? ? ? ? ? ? if ((bool)param_arr[3])
? ? ? ? ? ? ? ? ? ? ? ? stat._bytes_send += bytes;
? ? ? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? ? ? ? ? stat._bytes_recv += bytes;
? ? ? ? ? ? ? ? });
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? try
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? sock1.Shutdown(SocketShutdown.Both);
? ? ? ? ? ? ? ? ? ? sock2.Shutdown(SocketShutdown.Both);
? ? ? ? ? ? ? ? ? ? sock1.Close();
? ? ? ? ? ? ? ? ? ? sock2.Close();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? catch (Exception) { }
? ? ? ? ? ? }
? ? ? ? }


? ? ? ? private static void show_state()
? ? ? ? {
? ? ? ? ? ? StringBuilder curr_buf = new StringBuilder();
? ? ? ? ? ? curr_buf.AppendLine(program_ver);
? ? ? ? ? ? curr_buf.AppendLine(state._print_head);
? ? ? ? ? ? foreach (KeyValuePair<int, state> item in _state_dic)
? ? ? ? ? ? ? ? curr_buf.AppendLine(item.Value.ToString());
? ? ? ? ? ? if (_console_buf.Equals(curr_buf))
? ? ? ? ? ? ? ? return;
? ? ? ? ? ? Console.Clear();
? ? ? ? ? ? Console.WriteLine(curr_buf);
? ? ? ? ? ? _console_buf = curr_buf;
? ? ? ? }


? ? ? ? #endregion Methods
? ? ? ? private const string program_ver = @"[PortMapNet(0.1) ?http://www.baidu.com]
--------------------------------------------------";
? ? }
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388034.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388034.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388034.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python初學者_初學者使用Python的完整介紹

python初學者A magical art of teaching a computer to perform a task is called computer programming. Programming is one of the most valuable skills to have in this competitive world of computers. We, as modern humans, are living with lots of gadgets such as …

c# nat udp轉發

UdpClient myClient;Thread recvThread;//打開udp端口開始接收private void startRecv(int port){myClient new UdpClient(port);recvThread new Thread(new ThreadStart(receive));recvThread.Start();}//停止接收private void stopRecv(){recvThread.Abort();}private void…

【Code-Snippet】TextView

1. TextView文字過長&#xff0c;顯示省略號 【參考】 必須要同時設置XML和JAVA&#xff0c;而且&#xff0c;java中設置文字必須是在最后。 android:ellipsize"start|end|middle" //省略號的位置 android:singleLine"true" android:lines"2"…

Object 的靜態方法之 defineProperties 以及數據劫持效果

再提一下什么是靜態方法&#xff1a; 靜態方法&#xff1a;在類身上的方法&#xff0c;  動態方法:在實例身上的方法 Object.defineProperties(obj, props)obj&#xff1a;被添加屬性的對象props&#xff1a;添加或更新的屬性對象給對象定義屬性&#xff0c;如果存在該屬性&a…

Spring實現AOP的4種方式

Spring實現AOP的4種方式 先了解AOP的相關術語: 1.通知(Advice): 通知定義了切面是什么以及何時使用。描述了切面要完成的工作和何時需要執行這個工作。 2.連接點(Joinpoint): 程序能夠應用通知的一個“時機”&#xff0c;這些“時機”就是連接點&#xff0c;例如方法被調用時、…

如何使用Plotly在Python中為任何DataFrame繪制地圖的衛星視圖

Chart-Studio和Mapbox簡介 (Introduction to Chart-Studio and Mapbox) Folium and Geemap are arguably the best GIS libraries/tools to plot satellite-view maps or any other kinds out there, but at times they require an additional authorization to use the Google…

Java入門系列-26-JDBC

認識 JDBC JDBC (Java DataBase Connectivity) 是 Java 數據庫連接技術的簡稱&#xff0c;用于連接常用數據庫。 Sun 公司提供了 JDBC API &#xff0c;供程序員調用接口和類&#xff0c;集成在 java.sql 和 javax.sql 包中。 Sun 公司還提供了 DriverManager 類用來管理各種不…

3.19PMP試題每日一題

在房屋建造過程中&#xff0c;應該先完成衛生管道工程&#xff0c;才能進行電氣工程施工&#xff0c;這是一個&#xff1a;A、強制性依賴關系B、選擇性依賴關系C、外部依賴關系D、內部依賴關系 作者&#xff1a;Tracy19890201&#xff08;同微信號&#xff09;轉載于:https://…

Can't find temporary directory:internal error

今天我機子上的SVN突然沒有辦法進行代碼提交了&#xff0c;出現的錯誤提示信息為&#xff1a; Error&#xff1a;Cant find temporary directory:internal error 然后試了下其他的SVN源&#xff0c;發現均無法提交&#xff0c;并且update時也出現上面的錯誤信息。對比項目文件…

snowflake 數據庫_Snowflake數據分析教程

snowflake 數據庫目錄 (Table of Contents) Introduction 介紹 Creating a Snowflake Datasource 創建雪花數據源 Querying Your Datasource 查詢數據源 Analyzing Your Data and Adding Visualizations 分析數據并添加可視化 Using Drilldowns on Your Visualizations 在可視化…

jeesite緩存問題

jeesite&#xff0c;其框架主要為&#xff1a; 后端 核心框架&#xff1a;Spring Framework 4.0 安全框架&#xff1a;Apache Shiro 1.2 視圖框架&#xff1a;Spring MVC 4.0 服務端驗證&#xff1a;Hibernate Validator 5.1 布局框架&#xff1a;SiteMesh 2.4 工作流引擎…

高級Python:定義類時要應用的9種最佳做法

重點 (Top highlight)At its core, Python is an object-oriented programming (OOP) language. Being an OOP language, Python handles data and functionalities by supporting various features centered around objects. For instance, data structures are all objects, …

Java 注解 攔截器

場景描述&#xff1a;現在需要對部分Controller或者Controller里面的服務方法進行權限攔截。如果存在我們自定義的注解&#xff0c;通過自定義注解提取所需的權限值&#xff0c;然后對比session中的權限判斷當前用戶是否具有對該控制器或控制器方法的訪問權限。如果沒有相關權限…

醫療大數據處理流程_我們需要數據來大規模改善醫療流程

醫療大數據處理流程Note: the fictitious examples and diagrams are for illustrative purposes ONLY. They are mainly simplifications of real phenomena. Please consult with your physician if you have any questions.注意&#xff1a;虛擬示例和圖表僅用于說明目的。 …

What's the difference between markForCheck() and detectChanges()

https://stackoverflow.com/questions/41364386/whats-the-difference-between-markforcheck-and-detectchanges轉載于:https://www.cnblogs.com/chen8840/p/10573295.html

ASP.NET Core中使用GraphQL - 第七章 Mutation

ASP.NET Core中使用GraphQL - 目錄 ASP.NET Core中使用GraphQL - 第一章 Hello WorldASP.NET Core中使用GraphQL - 第二章 中間件ASP.NET Core中使用GraphQL - 第三章 依賴注入ASP.NET Core中使用GraphQL - 第四章 GrahpiQLASP.NET Core中使用GraphQL - 第五章 字段, 參數, 變量…

POM.xml紅叉解決方法

方法/步驟 1用Eclipse創建一個maven工程&#xff0c;網上有很多資料&#xff0c;這里不再啰嗦。 2右鍵maven工程&#xff0c;進行更新 3在彈出的對話框中勾選強制更新&#xff0c;如圖所示 4稍等片刻&#xff0c;pom.xml的紅叉消失了。。。

JS前臺頁面驗證文本框非空

效果圖&#xff1a; 代碼&#xff1a; 源代碼&#xff1a; <script type"text/javascript"> function check(){ var xm document.getElementById("xm").value; if(xm null || xm ){ alert("用戶名不能為空"); return false; } return …

python對象引用計數器_在Python中借助計數器對象對項目進行計數

python對象引用計數器前提 (The Premise) When we deal with data containers, such as tuples and lists, in Python we often need to count particular elements. One common way to do this is to use the count() function — you specify the element you want to count …

套接字設置為(非)阻塞模式

當socket 進行TCP 連接的時候&#xff08;也就是調用connect 時&#xff09;&#xff0c;一旦網絡不通&#xff0c;或者是ip 地址無效&#xff0c;就可能使整個線程阻塞。一般為30 秒&#xff08;我測的是20 秒&#xff09;。如果設置為非阻塞模式&#xff0c;能很好的解決這個…