我试图ping一个域列表以获得初始指示,如果它们存在 - 如果它们不存在我不会得到ping - 这会引发异常。没问题,除了某些原因,重定向也不会反击。
所以即时尝试获取异常url的http标头响应。但无论我得到403响应。任何想法?
private void hunt_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
string hostAddress = txtKeyword.Text;
string combined;
string[] strArray = new string[] { ".com", ".net", ".org", ".ca", ".gov" };
foreach (string str in strArray)
{
combined = hostAddress + str;
string result = string.Empty;
try
{
Ping ping = new Ping();
int timeout = 1500;
PingReply pingreply = ping.Send(combined, timeout);
if (pingreply != null && pingreply.Status.ToString() != "TimedOut")
{
result = "Address: " + pingreply.Address + "\r"
+ "Roundtrip Time: " + pingreply.RoundtripTime + "\r"
+ "TTL (Time To Live): " + pingreply.Options.Ttl + "\r"
+ "Buffer Size: " + pingreply.Buffer.Length + "\r";
listBox1.Items.Add(combined + " " + result);
}
else
{
listBox1.Items.Add(combined + " not found");
}
}
catch (Exception pingError)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www."+combined);
request.Method = "HEAD";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode status = response.StatusCode;
listBox1.Items.Add(status);
}
}
}
提前致谢
编辑Ping错误如下:
System.Net.NetworkInformation.PingException: An exception occurred during a Ping request. ---> System.Net.Sockets.SocketException: No such host is known
at System.Net.Dns.GetAddrInfo(String name)
at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)
at System.Net.Dns.GetHostAddresses(String hostNameOrAddress)
at System.Net.NetworkInformation.Ping.Send(String hostNameOrAddress, Int32 timeout, Byte[] buffer, PingOptions options)
--- End of inner exception stack trace ---
at System.Net.NetworkInformation.Ping.Send(String hostNameOrAddress, Int32 timeout, Byte[] buffer, PingOptions options)
at System.Net.NetworkInformation.Ping.Send(String hostNameOrAddress, Int32 timeout)
at DomainHunter.Form1.hunt_Click(Object sender, EventArgs e) in
答案 0 :(得分:1)
你的逻辑似乎是倒退的(正如我所读到的那样)。如果ping在没有获得响应时抛出异常,那么向服务器发送HEAD
请求通常是没有希望的,因为服务器可能不存在。
除了ping之外,对于你想要完成的事情来说,这并不是一个很好的选择。您可以在Dns.GetHostAddresses
之间进行组合(如评论中所建议的那样)并尝试打开到端口80和/或443的TCP连接(这适用于您要检查的站点)使用TCPClient
类来确定是否确实有服务器侦听发现的IP。没有什么能够真正验证实际上有服务器正在侦听您要检查的IP。它不检查URL是否有效,但是在证明服务器之后可能是HEAD
会有一个很好的补充。