【问题标题】:How to use HttpListener in Identifying the hostheader usage如何在识别主机头使用情况中使用 HttpListener
【发布时间】:2013-12-27 04:17:14
【问题描述】:

我试图找到一个主机头已经在使用中。所以我用一个 url 启动一个 HTTP 监听器。我预计会出现异常,因为具有主机标头的 url 已经注册。代码如下。 URL abc:81 已经启动并运行,但是侦听器无异常地启动和停止。谁能帮忙

 bool notUnderUse;  
 HttpListener listener = new HttpListener();
 listener.Prefixes.Add("http://abc:81/") ;
  try
   {
        listener.Start();
        listener.Stop();
        notUnderUse =  true;
    }
    catch (Exception ex)
     {
         notUnderUse = false;
     }

【问题讨论】:

  • 如果我提供 IP 地址端口号,它会按预期工作。我的意思是它已经抛出了正在使用的异常..但是不能正常使用主机头

标签: c# .net sockets http iis


【解决方案1】:

我用各种参考对下面的函数进行了编码,它运行良好。

 public static bool IsHostHeaderUnderUse(string ipAddress,string port, string hostname)
    {
        bool alreadyUnderUse = false;

        var header = string.Format("{0}:{1}:{2}", ipAddress, port, hostname);
        int? iisVersion = IISUtility.GetIISVersion();
        if (iisVersion.HasValue && iisVersion < 7)
        {
            DirectoryEntry iis = new DirectoryEntry("IIS://localhost/W3SVC");
            foreach (DirectoryEntry directoryEntry in iis.Children)
            {
                var bindings = directoryEntry.Properties["ServerBindings"];
                if (bindings.Contains(header))
                {
                    alreadyUnderUse = true;
                    break;
                }
            }
        }
        else
        {
            var serverManager = new ServerManager();
            foreach (Site site in serverManager.Sites)
            {
                foreach (var binding in site.Bindings)
                {
                    if (binding.BindingInformation.Contains(header))
                    {
                        alreadyUnderUse = true;
                        break;
                    }
                }
                if (alreadyUnderUse) { break; }
            }
        }
        return alreadyUnderUse;
    }

【讨论】:

    猜你喜欢
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 2020-07-13
    • 2019-10-10
    • 1970-01-01
    相关资源
    最近更新 更多