C# 端口转发

2023-05-16

业务需要跳转ip,又不想迁移程序,可以用此方法进行端口转发

这里写图片描述

 static void Main(string[] args)
        {
            //默认 127.0.0.1:8080 转发到 127.0.0.1:80
            var dk = new DuanKou("0.0.0.0",8080,"0.0.0.0",80);
            dk.Run();
            Console.ReadKey();
        }
 /// <summary>
    /// user => tcp1 => tcp2
    /// </summary>
    public class DuanKou
    {
        int localProt { get; set; }
        string localIp { get; set; }
        int TargetPort { get; set; }
        string TargetIp { get; set; }
        public DuanKou(string localIp,int localProt, string TargetIp, int TargetPort)
        {
            this.localIp = localIp;
            this.localProt = localProt;
            this.TargetIp = TargetIp;
            this.TargetPort = TargetPort;
        }

        public DuanKou()
        {
            this.localIp = "0.0.0.0" ;
            this.localProt = 8080;
            this.TargetIp = "0.0.0.0";
            this.TargetPort = 80;
        }

        public void Run()
        {
            //服务器IP地址  
            IPAddress ip = IPAddress.Parse(localIp);
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ;
            serverSocket.Bind(new IPEndPoint(ip, localProt));
            serverSocket.Listen(10000);   
            Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
            Thread myThread = new Thread(Listen);
            myThread.Start(serverSocket);
        }

        //监听客户端连接
        private void Listen(object obj)
        {
            Socket serverSocket = (Socket)obj;
            IPAddress ip = IPAddress.Parse(TargetIp);
            while (true)
            {
                Socket tcp1 = serverSocket.Accept();
                Socket tcp2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                tcp2.Connect(new IPEndPoint(ip, TargetPort));
                //目标主机返回数据
                ThreadPool.QueueUserWorkItem(new WaitCallback(SwapMsg), new thSock
                {
                    tcp1 = tcp2,
                    tcp2 = tcp1
                });
                //中间主机请求数据
                ThreadPool.QueueUserWorkItem(new WaitCallback(SwapMsg), new thSock
                {
                    tcp1 = tcp1,
                    tcp2 = tcp2
                });
            }
        }
        ///两个 tcp 连接 交换数据,一发一收
        public void SwapMsg(object obj)
        {
            thSock mSocket = (thSock)obj;
            while (true)
            {
                try
                {
                    byte[] result = new byte[1024];
                    int num = mSocket.tcp2.Receive(result, result.Length,SocketFlags.None);
                    if (num == 0) //接受空包关闭连接
                    {
                        if (mSocket.tcp1.Connected)
                        {
                            mSocket.tcp1.Close();
                        }
                        if (mSocket.tcp2.Connected)
                        {
                            mSocket.tcp2.Close();
                        }
                        break;
                    }
                    mSocket.tcp1.Send(result, num, SocketFlags.None);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    if (mSocket.tcp1.Connected)
                    {
                        mSocket.tcp1.Close();
                    }
                    if (mSocket.tcp2.Connected)
                    {
                        mSocket.tcp2.Close();
                    }
                    break;
                }
            }
        }

    }

    public class thSock
    {
        public Socket tcp1 { get; set; }
        public Socket tcp2 { get; set; }
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 端口转发 的相关文章

随机推荐

  • C# 连接SQL数据库

    测试代码 xff1a 控制台应用 using Newtonsoft Json using Newtonsoft Json Converters using System using System Collections Generic us
  • windows 添加开机启动项

    目录输入 xff1a C ProgramData Microsoft Windows Start Menu Programs StartUp 复制启动的软件到此目录下 xff0c 开机就能自动启动
  • 微软 dotnet.core 文档中文链接

    https docs microsoft com zh cn aspnet core
  • .net core 连接 mssql数据库

    跟在 net 里面一样的连接方法 xff0c 只是不能自动添加引用 dll 1 管理 nuget xff0c 添加以下两个引用 重要 PM gt Install Package System Data Common PM gt Instal
  • .net core 自动生成EF代码(net core 3.0更改)

    NuGet 管理控制台 输入 xff1a sqlserver EntityFramework xff0c Microsoft EntityFrameworkCore Tools PM gt Scaffold DbContext 34 Dat
  • .net core 搭载在 iis上

    官方文档 xff1a https docs microsoft com zh cn aspnet core publishing iis tabs 61 aspnetcore2x 点击打开链接
  • Centos Docker 从零开始(1)之安装 mssql

    Docker 从零开始 xff08 1 xff09 目标 xff1a 在 centos 上搭建docker xff0c 并且安装 mssql 数据库 xff0c 数据文件放在主机上 在centos上面安装docker 空白的centos 系
  • Java+Netty+WebRTC、语音、视频、屏幕共享【聊天室设计实践】

    背景 本文使用webtrc实现了一个简单的语音视频聊天室 支持多人音视频聊天 屏幕共享 环境配置 音视频功能需要在有Https协议的域名下才能获取到设备信息 xff0c 测试环境搭建Https服务参考Windows下Nginx配置SSL实现
  • Centos Docker 从零开始(2)之 mssql 的数据库文件保存在主机

    Docker mmsql新建数据库如果能够把数据库文件保存在主机上就好了 xff0c centos好像可以挂载的 docker 的 run 命令 xff1a v nginx www www 将主机中项目的目录www挂载到容器的 www 准备
  • SQL,LINQ,Lambda 语法对照图

    SQL LINQ Lambda 语法对照图
  • 利用反射构造工厂

    span class hljs keyword using span System span class hljs keyword using span System Reflection namespace Reflex factory
  • Go 调用windows 的UI库

    githurb 地址 xff1a https github com lxn
  • 股市的交易日(动态规划算法)

    股市的交易日 在股市的交易日中 xff0c 假设最多可进行两次买卖 即买和卖的次数均小于等于2 xff0c 规则是必须一笔成交后进行另一笔 即买 卖 买 卖的顺序进行 给出一天中的股票变化序列 xff0c 请写一个程序计算一天可以获得的最大
  • 排序算法

    第一种 xff1a 冒泡排序 每一次把最大的冒泡 span class hljs comment javasrcript 代码 xff1a span span class hljs function span class hljs keyw
  • javasrcript 实现的 get,post

    javasrcript 实现的 get xff0c post 1 创建ajax对象 2 连接到服务器 3 发送请求 4 接收返回值 代码如下 xff1a span class hljs comment 使用 span httpPost sp
  • Mycat入门(Windows环境)

    Mycat xff08 Windows环境 xff09 xff08 1 xff09 初入门 Mycat 是SQL集群中间件 xff0c 基于阿里开源的Cobar产品而研发 xff0c Cobar的稳定性 可靠性 优秀的架构和性能 1 MyC
  • C#Nuget 包官网链接

    C Nuget 包官网链接 https www nuget org downloads 使用文档 xff1a https docs microsoft com zh cn nuget create packages creating a p
  • Centos搭建 Git Server

    yum install y git git version git version 1 8 3 1 添加Git用户 useradd jggit passwd git git 新建库 Cd home jggit data mkdir p su
  • turnserver (coturn + redis) 配置ICE server 临时用户密码【实践】

    背景 前端连接turn服务时一般都需要设置账号密码 xff0c 由于都是在js中配置的 xff0c 长期凭据相对临时用户安全性会差很多 xff0c 本文通过程序生成临时的账号密码 xff0c 把临时凭据设置到Redis中 xff0c tur
  • C# 端口转发

    业务需要跳转ip xff0c 又不想迁移程序 xff0c 可以用此方法进行端口转发 span class hljs keyword static span span class hljs keyword void span Main spa