📄 srvrsock.cs
字号:
/*
* Author: $Author: tommieb $
* Date: $Date: 2005-10-02 16:31:17+01 $
* Id: $Id: SrvrSock.cs,v 1.1 2005-10-02 16:31:17+01 tommieb Exp tommieb $
* RCSFile: $RCSfile: SrvrSock.cs,v $
* Source: $Source: C:\\RCS\\C\\Documents\040and\040Settings\\tommieb\\My\040Documents\\SrvrRedirector\\SrvrSock.cs,v $
* Log History: $Log: SrvrSock.cs,v $
* Log History: Revision 1.1 2005-10-02 16:31:17+01 tommieb
* Log History: Added Console's for each event subscribed.
* Log History:
* Log History: Revision 1.0 2005-09-15 18:46:58+01 tommieb
* Log History: Initial Version.
* Log History:
*/
// Code copyrighted by Tom Brennan, 2005.
// As long as you don't remove this copyright notice, I, Tom Brennan, grants you hours of fun and pleasure
// with this code. As for licensing - hmmm, this is education!.....if you gain something from this, and
// it works - drop me a line, I would be delighted to hear from you. If you don't gain anything from this,
// oh well, ce la vie! :-)
// If it blows up your machine, causes your NIC to go haywire, monitor goes funny,
// or any other undocumented malfunctions not stated here, I aint responsible!
// Suggestions, criticisms, et al, please email me at tomas_o_braonain [at] hotmail [dot] com or
// wabbitty2002 [at] yahoo [dot] co [dot] uk OR even better, post code enhancements to me and
// I'll get this updated with your name in this copyright notice - fair huh? :-)
// Enjoy! :-)
// Grab the latest copy of Genghis (do Google for Chris Sells + Genghis project!),
#region Using's....
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
using Genghis;
using clp = Genghis.CommandLineParser;
#endregion
namespace SrvrRedirector{
#region SrvrRedirectorCmdLine Class
public class SrvrRedirectorCmdLine : CommandLineParser {
[clp.ValueUsage("Specify Source IP Server Host.", IgnoreCase = false, Optional = false)]
public string srcIP = "localhost";
[clp.ValueUsage("Specify the Source Server Port to listen on.", IgnoreCase = false, Optional = false)]
public int srcPort = 0;
[clp.ValueUsage("Specify Destination IP Server Host - IP format.", IgnoreCase = false, Optional = false)]
public string dstIP = "localhost";
[clp.ValueUsage("Specify the Destination Port to forward to.", IgnoreCase = false, Optional = false)]
public int dstPort = 0;
[clp.ValueUsage("Maximum Connections.", IgnoreCase = false, ValueName="10")]
public int maxConn = 10;
[clp.ValueUsage("Specify the Buffer Size in bytes.", IgnoreCase = false, ValueName="1024", Optional = true)]
public int bufSz = 1024;
[clp.ValueUsage("Specify Verbose logging", IgnoreCase = false, ValueName="false", Optional = true)]
public bool verboseFlag = false;
[clp.ValueUsage("Specify dumping of network packets", IgnoreCase = false, ValueName="false", Optional = true)]
public bool doDump = false;
[clp.ValueUsage("Specify Statistics", IgnoreCase = false, ValueName="false", Optional = true)]
public bool statisticsFlag = false;
}
#endregion
#region KickStarter Class
public class KickStarter{
static string RCSINFO = "$Id: SrvrSock.cs,v 1.1 2005-10-02 16:31:17+01 tommieb Exp tommieb $";
#region Main
[STAThread]
static void Main(string[] args){
SrvrRedirectorCmdLine cl = new SrvrRedirectorCmdLine();
int maxBufSz = -1;
if( !cl.ParseAndContinue(args) ) return;
if (Helper.IsHostDottedQuad(cl.srcIP) && Helper.IsHostDottedQuad(cl.dstIP)){
if (cl.srcPort == 0 || cl.srcPort < 1024){
Console.WriteLine("Invalid Source Port. Must be > 1024!");
return;
}
if (cl.dstPort == 0 || cl.dstPort < 1024){
Console.WriteLine("Invalid Destination Port. Must be > 1024!");
return;
}
if (cl.bufSz == 0 || cl.bufSz > int.MaxValue){
maxBufSz = 1024;
}else{
maxBufSz = cl.bufSz;
}
Console.WriteLine("SETUP>> srcIPAddr = {0}:{1}. dstIPAddr = {2}:{3}.", cl.srcIP, cl.srcPort, cl.dstIP, cl.dstPort);
Console.WriteLine("SETUP>> BUFFER Size: {0} bytes.", maxBufSz.ToString("###,###,###,###"));
SrvrRedirectorSocket srvrSock = new SrvrRedirectorSocket(cl.srcIP, cl.srcPort, cl.maxConn, cl.dstIP, cl.dstPort, maxBufSz, cl.verboseFlag, cl.doDump, cl.statisticsFlag);
if (cl.verboseFlag) SrvrRedirectorSocket.ServerMessages += new SrvrRedirectorSocket.ServerMessagesEventHandler(SrvrRedirectorSocket_ServerMessages);
if (cl.statisticsFlag) SrvrRedirectorSocket.Statistics += new SrvrRedirectorSocket.StatisticsEventHandler(SrvrRedirectorSocket_Statistics);
if (cl.doDump) SrvrRedirectorSocket.ServerDumpData += new SrvrRedirectorSocket.ServerDumpDataEventHandler(SrvrRedirectorSocket_ServerDumpData);
srvrSock.Connect();
if (srvrSock.SrvrRedirectOk){
Console.WriteLine("REDIR-SRVR>> Press any key to shutdown.");
Console.Read();
}
}else{
Console.WriteLine("Invalid IP Addresses for source/destination supplied");
return;
}
}
#endregion
private static void SrvrRedirectorSocket_ServerDumpData(object sender, ServerDumpDataEventArgs e) {
Console.WriteLine(e.ServerDumpData);
}
private static void SrvrRedirectorSocket_Statistics(object sender, StatisticsEventArgs e) {
Console.WriteLine(e.Statistics);
}
private static void SrvrRedirectorSocket_ServerMessages(object sender, ServerMessagesEventArgs e) {
Console.WriteLine(e.ServerMessage);
}
}
#endregion
#region Helper Class
public class Helper{
#region DumpBytes Method
public static void DumpBytes(byte[] dumpdBlock, string sMsg, int dumpdBlockLen){
int MaxChars = 16;
int LineCount = 0;
int byteCount = 0;
int nLoopCnt = 0;
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("=> Begin Dump. {0}; {1}\n", sMsg, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")));
while (byteCount != dumpdBlockLen){
int StartCount = LineCount * MaxChars;
sb.Append(string.Format("{0} ", StartCount.ToString("X4")));
string sAsciiDump = string.Empty;
for (nLoopCnt = 0; nLoopCnt < MaxChars; nLoopCnt++){
if (dumpdBlock[byteCount] < 128){
char ch = (char)dumpdBlock[byteCount];
if (char.IsLetterOrDigit(ch) || char.IsPunctuation(ch)){
sAsciiDump += char.ToString(ch);
}else{
sAsciiDump += ".";
}
}else{
sAsciiDump += ".";
}
sb.Append(string.Format("{0} ", dumpdBlock[byteCount++].ToString("X2")));
if (byteCount == dumpdBlockLen) break;
}
if (nLoopCnt < MaxChars){
for (int j = nLoopCnt + 1; j < MaxChars; j++){
sb.Append(" ");
}
}
sb.Append(string.Format("|{0}\n", sAsciiDump));
LineCount++;
}
sb.Append("=> End Dump.\n");
SrvrRedirectorSocket.OnServerDumpDataEventHandler(new ServerDumpDataEventArgs(sb.ToString()));
}
#endregion
#region IsHostDottedQuad Function
public static bool IsHostDottedQuad(string sHost){
Regex re = new Regex(@"(?<ip_addr_full_quad>(?<ip_addr_First>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<ip_addr_Second>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<ip_addr_Third>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<ip_addr_Fourth>2[0-4]\d|25[0-5]|[01]?\d\d?))", RegexOptions.Compiled);
Match m = re.Match(sHost);
if (m.Success) return true;
return false;
}
#endregion
}
#endregion
#region SrvrRedirectorSocket Class
public class SrvrRedirectorSocket{
private Socket _sockRedir = null;
private string _srcIPAddr = string.Empty;
private string _dstIPAddr = string.Empty;
private int _srcPort = -1;
private int _dstPort = -1;
private int _maxConn = -1;
private bool _verboseFlag = false;
private bool _doDump;
private static bool _bRedirOk = false;
private static bool _bStatistics = false;
private int _bufSz = -1;
public static Socket _StaticSockRedir = null;
public static int _StaticBufferSize;
public delegate void ServerMessagesEventHandler(object sender, ServerMessagesEventArgs e);
public static event ServerMessagesEventHandler ServerMessages;
public delegate void StatisticsEventHandler(object sender, StatisticsEventArgs e);
public static event StatisticsEventHandler Statistics;
public delegate void ServerDumpDataEventHandler(object sender, ServerDumpDataEventArgs e);
public static event ServerDumpDataEventHandler ServerDumpData;
#region Constructor
public SrvrRedirectorSocket(string srcIPAddr, int srcPort, int maxConn, string dstIPAddr, int dstPort, int bufSz, bool verboseFlag, bool doDump, bool statisticsFlag){
this._srcIPAddr = srcIPAddr;
this._srcPort = srcPort;
this._dstIPAddr = dstIPAddr;
this._dstPort = dstPort;
this._maxConn = maxConn;
this._verboseFlag = verboseFlag;
this._doDump = doDump;
_bStatistics = statisticsFlag;
_StaticBufferSize = this._bufSz = bufSz;
}
#endregion
#region SrvrRedirectOk Get Accessor
public bool SrvrRedirectOk{
get{ return _bRedirOk; }
}
#endregion
#region Connect Method
public void Connect(){
InitServerSocket();
if (_bRedirOk){
for (int i = 0; i < this._maxConn; i++){
Connection conn = new Connection(this._sockRedir, this._srcPort, this._verboseFlag, this._doDump);
conn.TargetConnectionIPAddr = this._dstIPAddr;
conn.TargetConnectionPort = this._dstPort;
this._sockRedir.BeginAccept(new AsyncCallback(conn.cbHandleIncomingExternalConnection), this._sockRedir);
}
}
}
#endregion
#region InitServerSocket Method
private void InitServerSocket(){
IPEndPoint myEndPoint = null;
try{
string hostName = this._srcIPAddr.ToLower();
IPHostEntry localMachineInfo = null;
try{
if (Helper.IsHostDottedQuad(hostName)){
localMachineInfo = Dns.GetHostByAddress(hostName);
OnServerMessagesEventHandler(new ServerMessagesEventArgs(string.Format("REDIR-SRVR>> Resolved {0} to HostName {1}", hostName, Dns.GetHostByAddress(hostName).HostName)));
}else{
localMachineInfo = Dns.Resolve(hostName);
}
}catch(SocketException){
OnServerMessagesEventHandler(new ServerMessagesEventArgs(string.Format("REDIR-SRVR>> Unable to resolve {0}. Terminating.", hostName)));
return;
}
int nHostAddressIndex = 0;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -