-
Notifications
You must be signed in to change notification settings - Fork 0
/
NetworkExtensions.cs
45 lines (44 loc) · 1.46 KB
/
NetworkExtensions.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
using System;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
namespace GServer
{
public static class NetworkExtensions
{
public static int FreeTcpPort()
{
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
public static IPEndPoint CreateIPEndPoint(string endPoint)
{
string[] ep = endPoint.Split(':');
if (ep.Length < 2) NetworkController.ShowException(new FormatException("Invalid endpoint format"));
IPAddress ip;
if (ep.Length > 2)
{
if (!IPAddress.TryParse(string.Join(":", ep, 0, ep.Length - 1), out ip))
{
NetworkController.ShowException(new FormatException("Invalid ip-adress"));
}
}
else
{
if (!IPAddress.TryParse(ep[0], out ip))
{
NetworkController.ShowException(new FormatException("Invalid ip-adress"));
}
}
int port;
if (!int.TryParse(ep[ep.Length - 1], NumberStyles.None, NumberFormatInfo.CurrentInfo, out port))
{
NetworkController.ShowException(new FormatException("Invalid port"));
}
return new IPEndPoint(ip, port);
}
}
}