예제 #1
0
        private bool TryParseHostHeader(out IPAddress address, out string host, out int port)
        {
            address = null;
            host    = null;
            port    = -1;

            var hostHeader = RequestHeaders.GetHeader("Host");

            if (String.IsNullOrWhiteSpace(hostHeader))
            {
                return(false);
            }

            // IPv6 (http://www.ietf.org/rfc/rfc2732.txt)
            if (hostHeader.StartsWith("[", StringComparison.Ordinal))
            {
                var portIndex = hostHeader.LastIndexOf("]:", StringComparison.Ordinal);
                if (portIndex != -1 && Int32.TryParse(hostHeader.Substring(portIndex + 2), out port))
                {
                    if (IPAddress.TryParse(hostHeader.Substring(1, portIndex - 1), out address))
                    {
                        host = null;
                        return(true);
                    }
                    host = hostHeader.Substring(0, portIndex + 1);
                    return(true);
                }
                if (hostHeader.EndsWith("]", StringComparison.Ordinal))
                {
                    if (IPAddress.TryParse(hostHeader.Substring(1, hostHeader.Length - 2), out address))
                    {
                        host = null;
                        port = -1;
                        return(true);
                    }
                }
            }
            else
            {
                // IPAddresses
                if (IPAddress.TryParse(hostHeader, out address))
                {
                    host = null;
                    port = -1;
                    return(true);
                }

                var portIndex = hostHeader.LastIndexOf(':');
                if (portIndex != -1 && Int32.TryParse(hostHeader.Substring(portIndex + 1), out port))
                {
                    host = hostHeader.Substring(0, portIndex);
                    return(true);
                }
            }

            // Plain
            host = hostHeader;
            return(true);
        }