How to get headers from 401 server error

I am writing a port scanner to detect web services running on a local network. Some of these web services require basic authentication - I don’t know the username / password for these services, I just want to list them, so I can’t provide credentials at this point. I am using the code:

                    var request = (HttpWebRequest)WebRequest.Create("http://" + req);
                    request.Referer = "";
                    request.Timeout = 3000;
                    request.UserAgent = "Mozilla/5.0";
                    request.AllowAutoRedirect = false;
                    request.Method = WebRequestMethods.Http.Head;

                    HttpWebResponse response = null;

                    try
                    {
                        response = (HttpWebResponse) request.GetResponse();
                        // I want to parse the headers here for the server name but as the exception is thrown the response object is null.

                    }
                    catch (Exception ex)
                    {
                        //401 error is caught here - response is null
                    }

Then I parse the server name from the returned headers - I know that they are returned because I see them with a violinist, but the HttpWebResponse object is null because the GetResponse () method throws an exception, Basically - how do I get it to not throw and exclude, and return headers with status code 401.

+5
source share
1 answer

WebException, ex.Response, .

+11

All Articles