Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Net;
- using System.Text.RegularExpressions;
- using System.Globalization;
- using System.Net.Sockets;
- using System.Runtime.InteropServices;
- using System.Diagnostics;
- using System.Net.NetworkInformation;
- namespace Lidgren.Network
- {
- public static class NetUtility
- {
- private static Regex s_regIP;
- public static IPAddress Resolve(string ipOrHost)
- {
- if (string.IsNullOrEmpty(ipOrHost))
- throw new ArgumentException("Supplied string must not be empty", "ipOrHost");
- ipOrHost = ipOrHost.Trim();
- if (s_regIP == null)
- {
- string expression = "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b";
- RegexOptions options = RegexOptions.Compiled;
- s_regIP = new Regex(expression, options);
- }
- IPAddress ipAddress = null;
- if (s_regIP.Match(ipOrHost).Success && IPAddress.TryParse(ipOrHost, out ipAddress))
- return ipAddress;
- IPHostEntry entry;
- try
- {
- entry = Dns.GetHostEntry(ipOrHost);
- if (entry == null)
- return null;
- foreach (IPAddress ipCurrent in entry.AddressList)
- {
- string sIP = ipCurrent.ToString();
- bool isIP = s_regIP.Match(sIP).Success && IPAddress.TryParse(sIP, out ipAddress);
- if (isIP)
- break;
- }
- if (ipAddress == null)
- return null;
- return ipAddress;
- }
- catch (SocketException ex)
- {
- if (ex.SocketErrorCode == SocketError.HostNotFound)
- {
- //LogWrite(string.Format(CultureInfo.InvariantCulture, "Failed to resolve host '{0}'.", ipOrHost));
- return null;
- }
- else
- {
- throw;
- }
- }
- }
- private static NetworkInterface GetNetworkInterface()
- {
- IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
- if (computerProperties == null)
- return null;
- NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
- if (nics == null || nics.Length < 1)
- return null;
- foreach (NetworkInterface adapter in nics)
- {
- if (adapter.OperationalStatus != OperationalStatus.Up)
- continue;
- if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback || adapter.NetworkInterfaceType == NetworkInterfaceType.Unknown)
- continue;
- if (!adapter.Supports(NetworkInterfaceComponent.IPv4))
- continue;
- return adapter;
- }
- return null;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment