在c#中是否有办法检查应用程序是否在localhost上运行(而不是生产服务器)?
我正在编写一个群发邮件程序,需要使用某个邮件队列才能在localhost上运行.
if (Localhost)
{
Queue = QueueLocal;
}
else
{
Queue = QueueProduction;
}
Run Code Online (Sandbox Code Playgroud)
Tom*_*dia 60
由于评论有正确的解决方案,我将把它作为答案发布:
HttpContext.Current.Request.IsLocal
Run Code Online (Sandbox Code Playgroud)
Tod*_*her 32
怎么样的:
public static bool OnTestingServer()
{
string host = HttpContext.Current.Request.Url.Host.ToLower();
return (host == "localhost");
}
Run Code Online (Sandbox Code Playgroud)
the*_*tuf 17
看看这是否有效:
public static bool IsLocalIpAddress(string host)
{
try
{ // get host IP addresses
IPAddress[] hostIPs = Dns.GetHostAddresses(host);
// get local IP addresses
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
// test if any host IP equals to any local IP or to localhost
foreach (IPAddress hostIP in hostIPs)
{
// is localhost
if (IPAddress.IsLoopback(hostIP)) return true;
// is local address
foreach (IPAddress localIP in localIPs)
{
if (hostIP.Equals(localIP)) return true;
}
}
}
catch { }
return false;
}
Run Code Online (Sandbox Code Playgroud)
参考:http://www.csharp-examples.net/local-ip/
Localhost IP地址是常量,您可以使用它来确定它是localhost还是远程用户.
但要注意,如果您登录到生产服务器,它也将被视为localhost.
这包括IP v.4和v.6:
public static bool isLocalhost( )
{
string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
return (ip == "127.0.0.1" || ip == "::1");
}
Run Code Online (Sandbox Code Playgroud)
要完全确定运行代码的服务器,可以使用MAC地址:
public string GetMACAddress()
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty)// only return MAC Address from first card
{
IPInterfaceProperties properties = adapter.GetIPProperties();
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
} return sMacAddress;
}
Run Code Online (Sandbox Code Playgroud)
来自:http://www.c-sharpcorner.com/uploadfile/ahsanm.m/how-to-get-the-mac-address-of-system-using-Asp-NetC-Sharp/
例如,与web.config中的MAC地址进行比较.
public static bool isLocalhost( )
{
return GetMACAddress() == System.Configuration.ConfigurationManager.AppSettings["LocalhostMAC"].ToString();
}
Run Code Online (Sandbox Code Playgroud)
不幸的是HttpContext.HttpRequest.IsLocal(),核心中不再有。
但是在 .Net 中检查了原始实现之后,通过检查重新实现相同的行为是很容易的HttpContext.Connection:
private bool IsLocal(ConnectionInfo connection)
{
var remoteAddress = connection.RemoteIpAddress.ToString();
// if unknown, assume not local
if (String.IsNullOrEmpty(remoteAddress))
return false;
// check if localhost
if (remoteAddress == "127.0.0.1" || remoteAddress == "::1")
return true;
// compare with local address
if (remoteAddress == connection.LocalIpAddress.ToString())
return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)