summaryrefslogtreecommitdiff
path: root/Impostor-dev/src/Impostor.Server/Utils/IpUtils.cs
blob: 649d45ae6c2dd756dfd41f7e76bc57c4d342d047 (plain)
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
using System.Linq;
using System.Net;
using System.Net.Sockets;
using Impostor.Api;

namespace Impostor.Server.Utils
{
    internal static class IpUtils
    {
        public static string ResolveIp(string ip)
        {
            // Check if valid ip was entered.
            if (!IPAddress.TryParse(ip, out var ipAddress))
            {
                // Attempt to resolve DNS.
                try
                {
                    var hostAddresses = Dns.GetHostAddresses(ip);
                    if (hostAddresses.Length == 0)
                    {
                        throw new ImpostorConfigException($"Invalid IP Address entered '{ip}'.");
                    }

                    // Use first IPv4 result.
                    ipAddress = hostAddresses.First(x => x.AddressFamily == AddressFamily.InterNetwork);
                }
                catch (SocketException)
                {
                    throw new ImpostorConfigException($"Failed to resolve hostname '{ip}'.");
                }
            }

            // Only IPv4.
            if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
            {
                throw new ImpostorConfigException($"Invalid IP Address entered '{ipAddress}', only IPv4 is supported by Among Us.");
            }

            return ipAddress.ToString();
        }
    }
}