-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
243 lines (211 loc) · 9.85 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
public class myTCPListener
{
static ConsoleColor progInfo = ConsoleColor.Yellow;
static ConsoleColor defaultColor = Console.ForegroundColor;
static ConsoleColor connectionColor = ConsoleColor.Green;
static ConsoleColor exceptionColor = ConsoleColor.Red;
static ConsoleColor helpColor = ConsoleColor.Cyan;
static bool logging;
static bool verbose;
static void Main(string[] args)
{
try
{
Console.ForegroundColor = progInfo;
Console.WriteLine();
Console.WriteLine("---------------------------------------------------------");
Console.WriteLine(" MyTCPlistener v{0} {1}", Assembly.GetExecutingAssembly().GetName().Version, " coded by Vassilis Ioannidis");
Console.WriteLine(" Blog: www.sqltattoo.com - GitHub: github.com/SQLtattoo");
Console.WriteLine();
Console.WriteLine(" To get help type: myTCPlistener --help");
Console.WriteLine("---------------------------------------------------------");
Console.WriteLine();
//check to see if the user requested the help functionality
if (args.Length>0 && args[0].ToString()=="--help")
{
Console.ForegroundColor = helpColor;
//print the parameter-text with samples
PrintParametersText();
Console.ForegroundColor = defaultColor;
return;
}
// set the defaults
int port = 20907;
IPAddress addr = IPAddress.Any;
logging = false;
verbose = true;
Console.ForegroundColor = connectionColor;
//read the args array to see if any parameters have been passed in by the user
if (args.Length > 0)
{
addr = IPAddress.Parse((args[0] == "*"? "0.0.0.0":args[0]));
port = Int32.Parse(args[1]);
logging = (args[2] == "0") ? false : true;
verbose = (args[3] == "0") ? false : true;
}
Console.WriteLine("Running parameters: ");
Console.WriteLine("-------------------------------------------------");
Console.WriteLine(" IP address listening on: {0}", addr);
Console.WriteLine(" Port listening to: {0}", port);
Console.WriteLine(" Is logging to file enabled: {0}", logging);
Console.WriteLine(" Display information on screen: {0}", verbose);
Console.WriteLine();
//initiate the listener
TcpListener server = new TcpListener(addr, port);
// Start listening for client requests
server.Start();
// Buffer for reading data
byte[] bytes = new byte[1024];
string data;
Console.WriteLine("Started listening... //Break execution with ^C (Ctrl+C)");
//Enter the listening loop
while (true)
{
// Perform a blocking call to accept requests.
// You could also use server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
VerboseOrLogging("Connection from " + client.Client.RemoteEndPoint.ToString() +" established @" + System.DateTime.UtcNow, logging);
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
i = stream.Read(bytes, 0, bytes.Length);
while (i != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
VerboseOrLogging(" Received: " + data, logging);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
VerboseOrLogging(" Sent: " + data, logging);
i = stream.Read(bytes, 0, bytes.Length);
}
Console.WriteLine("...", addr, port);
// Shutdown the listener and end the connection
client.Close();
}
}
catch (SocketException ex)
{
Console.ForegroundColor = exceptionColor;
FileLogging(" SocketException: " + ex, true);
Console.WriteLine(" Exception occurred. Check the log.");
}
catch (Exception ex)
{
Console.ForegroundColor = exceptionColor;
FileLogging(" Exception: " + ex, true);
Console.WriteLine(" Exception occurred. Check the log.");
}
finally
{
Console.ForegroundColor = defaultColor;
}
Console.ForegroundColor = defaultColor;
}
static void VerboseOrLogging(string loginfo, bool toFile)
{
try
{
if(verbose)
{
Console.WriteLine(loginfo);
}
if (toFile)
{
FileLogging(loginfo, false);
}
}
catch
{
//homework guys :)
}
}
static void FileLogging(string loginfo, bool exceptionLog)
{
try
{
//get the path where the executable is running in
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
//create a StreamWriter object to assign the log file that we will write in
StreamWriter sw;
//open the log file for create or append
sw = File.AppendText(path + "\\myTCPlistener.log");
//flush automatically the contents of the stream to the file
sw.AutoFlush = true;
if (!exceptionLog)
{
sw.WriteLine(" " + loginfo);
sw.WriteLine("-----------------------------------------------------------------------------------");
}
else
{
sw.WriteLine("--EXCEPTION STARTS {0} ------------------------------------------------", System.DateTime.UtcNow);
sw.WriteLine(loginfo);
sw.WriteLine("--EXCEPTION ENDS {0} --------------------------------------------------", System.DateTime.UtcNow);
}
//close the StreamWriter object otherwise you will get exceptions
sw.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error while trying to log. {0}", ex);
}
}
static void PrintParametersText()
{
try
{
Console.WriteLine("PURPOSE: ");
Console.WriteLine("I just wanted to have the flexibility to spin up a listener on any IP bound and any port to check connectivity between 2 hosts while having a bit of a fun coding 8-)");
Console.WriteLine();
Console.WriteLine("LICENSE:");
Console.WriteLine("To be used under MIT license. More on this here https://en.wikipedia.org/wiki/MIT_License");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("-----------------------------------------------------");
Console.WriteLine(">>>> Help is on the way! >>>>");
Console.WriteLine("-----------------------------------------------------");
Console.WriteLine("The listener can be run with the following arguments:");
Console.WriteLine("Parameter 1: for specific IP address on the host to listen to i.e. 192.168.2.55 or '*' for all IPs (default)");
Console.WriteLine("Parameter 2: for port other than 20907(default). Port must be open for incoming on the firewall of the host");
Console.WriteLine("Parameter 3: file logging: 0: disable(default), 1: enable. (myTCPlistener.log)");
Console.WriteLine("Parameter 4: display information: 0: silent mode, 1: verbose(default)");
Console.WriteLine();
Console.WriteLine("Examples 1: No parameters:");
Console.Write(" run the following command: ");
Console.ForegroundColor = defaultColor;
Console.WriteLine("myTCPlistener.exe");
Console.ForegroundColor = helpColor;
Console.WriteLine();
Console.WriteLine("Examples 2: With parameters: ");
Console.WriteLine(" For any IP on the listener host on port 20000, enable logging to file and do not show info on screen");
Console.WriteLine(" run the following command: ");
Console.Write(" run the following command: ");
Console.ForegroundColor = defaultColor;
Console.WriteLine("myTCPlistener.exe * 20000 1 0");
Console.ForegroundColor = helpColor;
Console.WriteLine();
Console.WriteLine("Examples 3: With parameters: ");
Console.WriteLine(" A specific IP 192.168.2.20 on the listener host on port 20000, enable logging to file, do not show info on screen");
Console.WriteLine(" run the following command: ");
Console.Write(" run the following command: ");
Console.ForegroundColor = defaultColor;
Console.WriteLine("myTCPlistener.exe \"192.168.2.20\" 20000 1 0");
Console.ForegroundColor = helpColor;
Console.WriteLine("IMPORTANT! You either run with no parameters or you input all 4 parameters");
}
catch
{
//what can go wrong here, right? :)
}
}
}