-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathPortCheckingPatch.cs
More file actions
44 lines (40 loc) · 1.4 KB
/
PortCheckingPatch.cs
File metadata and controls
44 lines (40 loc) · 1.4 KB
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
using System;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using NLog;
using Torch.Managers.PatchManager;
namespace Torch.Patches
{
[PatchShim]
internal static class PortCheckingPatch
{
private static Logger _log = LogManager.GetCurrentClassLogger();
public static void Patch(PatchContext ctx)
{
_log.Info("performing port check");
ctx.GetPattern(typeof(Sandbox.Engine.Multiplayer.MyDedicatedServerBase).GetMethod("Initialize", BindingFlags.NonPublic | BindingFlags.Instance))
.Prefixes.Add(typeof(PortCheckingPatch).GetMethod(nameof(Initialize)));
}
public static void Initialize(IPEndPoint serverEndpoint)
{
_log.Info("Checking if port is in use");
// Create a TcpListener on localhost at the specified port
TcpListener tcpListener = null;
try
{
tcpListener = new TcpListener(IPAddress.Loopback, serverEndpoint.Port);
tcpListener.Start();
}
catch (SocketException)
{
// If an exception is caught, then the port is in use
throw new Exception("Port is in use, check if another server is running on the same port");
}
finally
{
tcpListener?.Stop();
}
}
}
}