-
Notifications
You must be signed in to change notification settings - Fork 5
/
RTNetwork.cs
515 lines (461 loc) · 18.8 KB
/
RTNetwork.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
// Realtime SDK for Qualisys Track Manager. Copyright 2015-2018 Qualisys AB
//
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System;
namespace QTMRealTimeSDK.Network
{
public enum ResponseType
{
success,
timeout,
disconnect,
error
}
internal struct Response
{
internal int received;
internal ResponseType type;
internal Response(ResponseType type, int received)
{
this.type = type;
this.received = received;
}
public static implicit operator bool(Response value)
{
return value.type == ResponseType.success;
}
public static implicit operator ResponseType(Response value)
{
return value.type;
}
}
internal class RTNetwork : IDisposable
{
private UdpClient mUDPClient = null;
private UdpClient mUDPBroadcastClient = null;
private TcpClient mTCPClient = null;
string mErrorString;
private SocketError mSocketError = SocketError.NotConnected;
/// <summary>
/// Default constructor
/// </summary>
internal RTNetwork()
{
}
~RTNetwork()
{
Dispose(false);
}
/// <summary>
/// Connect TCP socket to a server.
/// </summary>
/// <param name="serverAddr">IP or hostname of server.</param>
/// <param name="port">Port that TCP should use.</param>
/// <returns>True if connection is successful otherwise false</returns>
internal bool Connect(string serverAddr, int port)
{
try
{
IPAddress[] serverIP = Dns.GetHostAddresses(serverAddr);
if (serverIP.Length <= 0)
{
mErrorString = "Error looking up host name";
return false;
}
mTCPClient = new TcpClient();
// Adding timeout to connection, otherwise system sometimes
// hangs when attempting to connect to an invalid host; programs won't
// continue after mTCPClient.Connect() until a new request is made
mTCPClient.SendTimeout = 500;
mTCPClient.Connect(serverIP[0], port);
// Disable Nagle's algorithm
mTCPClient.NoDelay = true;
}
catch (SocketException e)
{
mErrorString = e.Message;
mSocketError = e.SocketErrorCode;
if (mTCPClient != null)
{
mTCPClient.Close();
}
return false;
}
return true;
}
/// <summary>
/// Closes selected sockets(command(TCP), stream(UDP) and broadcast(UDP)). All sockets closed by default.
/// </summary>
internal void Disconnect(bool tcp = true, bool udp = true, bool udpBroadcast = true)
{
if (tcp && mTCPClient != null)
{
if (mTCPClient.Client != null)
{
// If this is not checked, I keep getting a "The socket is not connected" exception
if (mTCPClient.Client.Connected)
{
mTCPClient.Client.Shutdown(SocketShutdown.Send);
}
}
mTCPClient.Close();
mTCPClient = null;
}
if (udp && mUDPClient != null)
{
mUDPClient.Close();
mUDPClient = null;
}
if (udpBroadcast && mUDPBroadcastClient != null)
{
mUDPBroadcastClient.Close();
mUDPBroadcastClient = null;
}
}
/// <summary>
/// Check if TCP socket is connected.
/// </summary>
/// <returns>true if TCP socket is connected to a server</returns>
internal bool IsConnected()
{
return (mTCPClient != null && mTCPClient.Connected);
}
/// <summary>
/// Creates an UDP socket for streaming or to send broadcast packet for server discovery
/// </summary>
/// <param name="udpPort">Port to use for socket. set to 0 to get a free port automatically</param>
/// <param name="broadcast">Should socket be used for sending broadcast? Default is false</param>
/// <returns>True if socket creation was successful</returns>
internal bool CreateUDPSocket(ref ushort udpPort, bool broadcast = false)
{
if (udpPort == 0 || udpPort > 1023)
{
IPEndPoint e = new IPEndPoint(IPAddress.Any, udpPort);
UdpClient tempSocket = new UdpClient(e);
tempSocket.Client.Blocking = false;
udpPort = (ushort)((IPEndPoint)tempSocket.Client.LocalEndPoint).Port;
if (broadcast)
{
tempSocket.Client.EnableBroadcast = true;
mUDPBroadcastClient = tempSocket;
}
else
{
mUDPClient = tempSocket;
}
return true;
}
else
{
mErrorString = "Please use port outside of system port range (1024 or greater)";
return false;
}
}
internal Response ReceiveBroadcast(ref byte[] receivebuffer, int bufferSize, ref EndPoint remoteEP, int timeout)
{
if (mUDPBroadcastClient == null)
{
mErrorString = "No clients to receive from.";
return new Response(ResponseType.error, 0);
}
try
{
List<Socket> receiveList = new List<Socket>();
List<Socket> errorList = new List<Socket>();
if (mUDPBroadcastClient != null)
{
receiveList.Add(mUDPBroadcastClient.Client);
errorList.Add(mUDPBroadcastClient.Client);
}
Socket.Select(receiveList, null, errorList, timeout);
if (mUDPBroadcastClient != null && errorList.Contains(mUDPBroadcastClient.Client))
{
// Error from broadcast socket
mErrorString = "Error reading from Broadcast UDP socket";
return new Response(ResponseType.error, 0);
}
else if (mUDPBroadcastClient != null && receiveList.Contains(mUDPBroadcastClient.Client))
{
// Receive data from broadcast socket
int received = mUDPBroadcastClient.Client.ReceiveFrom(receivebuffer, bufferSize, SocketFlags.None, ref remoteEP);
return new Response((received == 0) ? ResponseType.disconnect : ResponseType.success, received);
}
else
{
return new Response(ResponseType.timeout, 0);
}
}
catch (SocketException exception)
{
// Ignore and return
mErrorString = exception.Message;
}
return new Response(ResponseType.error, 0);
}
internal Response Receive(ref byte[] receivebuffer, int offset, int bufferSize, bool header, int timeout)
{
var response = new Response(ResponseType.error, 0);
try
{
List<Socket> receiveList = new List<Socket>();
List<Socket> errorList = new List<Socket>();
if (mTCPClient != null)
{
receiveList.Add(mTCPClient.Client);
errorList.Add(mTCPClient.Client);
}
if (mUDPClient != null)
{
receiveList.Add(mUDPClient.Client);
errorList.Add(mUDPClient.Client);
}
if (receiveList.Count == 0)
{
receivebuffer = null;
mErrorString = "No clients to receive from.";
return new Response(ResponseType.error, 0);
}
Socket.Select(receiveList, null, errorList, timeout);
if (mTCPClient != null && errorList.Contains(mTCPClient.Client))
{
// Error from TCP socket
mErrorString = "Error reading from TCP socket";
return new Response(ResponseType.error, 0);
}
else if (mTCPClient != null && receiveList.Contains(mTCPClient.Client))
{
// Receive data from TCP socket
int received = mTCPClient.Client.Receive(receivebuffer, offset, header ? RTProtocol.Constants.PACKET_HEADER_SIZE : bufferSize, SocketFlags.None);
return new Response((received == 0) ? ResponseType.disconnect : ResponseType.success, received);
}
else if (mUDPClient != null && errorList.Contains(mUDPClient.Client))
{
// Error from UDP socket
mErrorString = "Error reading from UDP socket";
return new Response(ResponseType.error, 0);
}
else if (mUDPClient != null && receiveList.Contains(mUDPClient.Client))
{
// Receive data from UDP socket
int received = mUDPClient.Client.Receive(receivebuffer, offset, bufferSize, SocketFlags.None);
return new Response((received == 0) ? ResponseType.disconnect : ResponseType.success, received);
}
else
{
return new Response(ResponseType.timeout, 0);
}
}
catch (SocketException exception)
{
// Ignore and return
mErrorString = exception.Message;
}
return new Response(ResponseType.error, 0);
}
/// <summary>
/// Send data from TCP socket.
/// </summary>
/// <param name="sendBuffer">data to send.</param>
/// <param name="bufferSize">size of data to send.</param>
/// <returns>true if data was sent successfully otherwise false</returns>
internal bool Send(byte[] sendBuffer, int bufferSize)
{
int sentData = 0;
try
{
sentData += mTCPClient.Client.Send(sendBuffer);
}
catch (SocketException e)
{
mErrorString = e.Message;
mSocketError = e.SocketErrorCode;
return false;
}
return true;
}
/// <summary>
/// Try and get all the local IP addresses
/// </summary>
/// <returns></returns>
private static List<IPAddress> GetLocalIPAddresses()
{
try
{
List<IPAddress> localIPs = new List<IPAddress>();
var hostName = Dns.GetHostName();
var host = Dns.GetHostEntry(hostName);
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIPs.Add(ip);
}
}
return localIPs;
}
catch (Exception)
{
// Ignore exception
}
return null;
}
/// <summary>
/// Send data over UDP via broadcast IP
/// </summary>
/// <param name="sendBuffer"> Buffer to send over UDP. </param>
/// <param name="bufferSize"> Size of buffer(should be 10)</param>
/// <param name="discoverPort"> Port for server to respond on. </param>
/// <returns></returns>
internal bool SendUDPBroadcast(byte[] sendBuffer, int bufferSize, int discoverPort = RTProtocol.Constants.STANDARD_BROADCAST_PORT)
{
if (mUDPBroadcastClient == null)
return false;
try
{
var nics = NetworkInterface.GetAllNetworkInterfaces();
if (nics.Length > 0)
{
foreach (NetworkInterface nic in nics)
{
try
{
if (nic.NetworkInterfaceType != NetworkInterfaceType.Ethernet &&
nic.NetworkInterfaceType != NetworkInterfaceType.Wireless80211)
continue;
foreach (UnicastIPAddressInformation ip in nic.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
continue;
IPAddress ipv4Mask;
try
{
ipv4Mask = ip.IPv4Mask;
}
catch (Exception)
{
ipv4Mask = IPAddress.Parse("255.255.255.0");
}
var broadcastAddress = ip.Address.GetBroadcastAddress(ipv4Mask);
if (broadcastAddress != null)
{
IPEndPoint e = new IPEndPoint(broadcastAddress, discoverPort);
mUDPBroadcastClient.Client.SendTo(sendBuffer, bufferSize, 0, e);
}
}
}
catch (Exception)
{
// Ignore broadcast failure, since we might have more IPs to send to
}
}
}
else
{
var localIPs = GetLocalIPAddresses();
foreach (var ip in localIPs)
{
try
{
var ipv4Mask = IPAddress.Parse("255.255.255.0");
var broadcastAddress = ip.GetBroadcastAddress(ipv4Mask);
if (broadcastAddress != null)
{
IPEndPoint e = new IPEndPoint(broadcastAddress, discoverPort);
mUDPBroadcastClient.Client.SendTo(sendBuffer, bufferSize, 0, e);
}
}
catch (Exception)
{
// Ignore broadcast failure, since we might have more IPs to send to
}
}
}
}
catch (SocketException e)
{
mSocketError = e.SocketErrorCode;
mErrorString = e.Message;
return false;
}
catch (Exception e)
{
mErrorString = e.Message;
return false;
}
return true;
}
/// <summary>
/// Error string related to errors that could have occurred during execution of commands
/// </summary>
/// <returns>string with error description</returns>
internal string GetErrorString()
{
return mErrorString;
}
/// <summary>
/// More specific error related to socket error occurred during execution of commands.
/// </summary>
/// <returns>Socket error</returns>
internal SocketError GetError()
{
return mSocketError;
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
Disconnect();
}
disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool disposed = false;
}
internal static class IPAddressExtensions
{
internal static IPAddress GetBroadcastAddress(this IPAddress address, IPAddress subnetMask)
{
if (address == null || subnetMask == null)
return null;
byte[] ipAddressBytes = address.GetAddressBytes();
byte[] subnetMaskBytes = subnetMask.GetAddressBytes();
if (ipAddressBytes.Length != subnetMaskBytes.Length)
throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
byte[] broadcastAddress = new byte[ipAddressBytes.Length];
for (int i = 0; i < broadcastAddress.Length; i++)
{
broadcastAddress[i] = (byte)(ipAddressBytes[i] | (subnetMaskBytes[i] ^ 255));
}
return new IPAddress(broadcastAddress);
}
internal static IPAddress GetNetworkAddress(this IPAddress address, IPAddress subnetMask)
{
byte[] ipAddressBytes = address.GetAddressBytes();
byte[] subnetMaskBytes = subnetMask.GetAddressBytes();
if (ipAddressBytes.Length != subnetMaskBytes.Length)
throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
byte[] broadcastAddress = new byte[ipAddressBytes.Length];
for (int i = 0; i < broadcastAddress.Length; i++)
{
broadcastAddress[i] = (byte)(ipAddressBytes[i] & (subnetMaskBytes[i]));
}
return new IPAddress(broadcastAddress);
}
internal static bool IsInSameSubnet(this IPAddress address2, IPAddress address, IPAddress subnetMask)
{
IPAddress network1 = address.GetNetworkAddress(subnetMask);
IPAddress network2 = address2.GetNetworkAddress(subnetMask);
return network1.Equals(network2);
}
}
}