Commit 0d628c6d authored by justcoding121's avatar justcoding121

refactor local IP check

parent 2d076556
......@@ -28,36 +28,44 @@ namespace Titanium.Web.Proxy.Helpers
internal static bool IsLocalIpAddress(string hostName)
{
bool isLocalhost = false;
hostName = hostName.ToLower();
var localhost = Dns.GetHostEntry("127.0.0.1");
if (hostName == localhost.HostName)
if (hostName == "127.0.0.1"
|| hostName == "localhost")
{
var hostEntry = Dns.GetHostEntry(hostName);
isLocalhost = hostEntry.AddressList.Any(IPAddress.IsLoopback);
return true;
}
if (!isLocalhost)
var localhostDnsName = Dns.GetHostName().ToLower();
//if hostname matches current machine DNS name
if (hostName == localhostDnsName)
{
localhost = Dns.GetHostEntry(Dns.GetHostName());
return true;
}
var isLocalhost = false;
IPHostEntry hostEntry = null;
//check if parsable to an IP Address
if (IPAddress.TryParse(hostName, out var ipAddress))
{
isLocalhost = localhost.AddressList.Any(x => x.Equals(ipAddress));
hostEntry = Dns.GetHostEntry(localhostDnsName);
isLocalhost = hostEntry.AddressList.Any(x => x.Equals(ipAddress));
}
if (!isLocalhost)
{
try
{
var hostEntry = Dns.GetHostEntry(hostName);
isLocalhost = localhost.AddressList.Any(x => hostEntry.AddressList.Any(x.Equals));
hostEntry = Dns.GetHostEntry(hostName);
isLocalhost = hostEntry.AddressList.Any(x => hostEntry.AddressList.Any(x.Equals));
}
catch (SocketException)
{
}
}
}
return isLocalhost;
}
......
......@@ -229,16 +229,12 @@ namespace Titanium.Web.Proxy.Network.Tcp
ProxyServer proxyServer, IPEndPoint upStreamEndPoint, ExternalProxy externalProxy,
CancellationToken cancellationToken)
{
if (remoteHostName == "localhost"
|| remoteHostName == "127.0.0.1"
|| remoteHostName == Dns.GetHostName())
{
if (server.ProxyEndPoints.Any(x => x.Port == remotePort))
//deny connection to proxy end points to avoid infinite connection loop.
if (server.ProxyEndPoints.Any(x => x.Port == remotePort)
&& NetworkHelper.IsLocalIpAddress(remoteHostName))
{
throw new Exception($"A client is making HTTP request to one of the listening ports of this proxy {remoteHostName}:{remotePort}");
}
}
bool useUpstreamProxy = false;
......
......@@ -442,7 +442,7 @@ namespace Titanium.Web.Proxy
systemProxySettingsManager.SetProxy(
Equals(endPoint.IpAddress, IPAddress.Any) |
Equals(endPoint.IpAddress, IPAddress.Loopback)
? "127.0.0.1"
? "localhost"
: endPoint.IpAddress.ToString(),
endPoint.Port,
protocolType);
......@@ -545,8 +545,7 @@ namespace Titanium.Web.Proxy
var protocolToRemove = ProxyProtocolType.None;
foreach (var proxy in proxyInfo.Proxies.Values)
{
if ((proxy.HostName == "127.0.0.1"
|| proxy.HostName.EqualsIgnoreCase("localhost"))
if (NetworkHelper.IsLocalIpAddress(proxy.HostName)
&& ProxyEndPoints.Any(x => x.Port == proxy.Port))
{
protocolToRemove |= proxy.ProtocolType;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment