从URL获取IP地址时出现套接字错误
问题描述:
我正在尝试从用户那里获取网站,并获取用户输入的任何网站的IP地址。我有一个用户可以进入任何网站的文本框。如果用户输入“www.Google.com”,那么该文本将转到System.Net.Dns.GetHostAddresses(Convert.ToString(urlTextbox));
但是,当我运行该程序并测试程序时,它会给我一个套接字未处理的错误。没有找到这样的主机。 我能做些什么来解决这个问题?从URL获取IP地址时出现套接字错误
这就是我想要的东西: 这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace Challenger
{
public partial class Form1 : Form
{
int ipWidth;
string x;
public Form1()
{
InitializeComponent();
urlTextbox.Text ="www.";
ipLabelText();
}
private void button2_Click(object sender, EventArgs e)
{
System.Net.IPAddress[] addresses =
System.Net.Dns.GetHostAddresses(Convert.ToString(urlTextbox));
string ipTextLength = Convert.ToString(addresses[0]);
//Stores the amount of digits
ipWidth = ipTextLength.Length;
//Puts ip into a string-> Label for Display
label2.Text = Convert.ToString(addresses[0]);
label2.Location = new Point(80, 20);
}
public void ipLabelText()
{
label2.Parent = panel1;
label2.BackColor = Color.Transparent;
label2.ForeColor = Color.White;
}
}
}
//Porting LOIC Android Application in C#
答
GetHostByAddress需要一个IP地址,并返回一个主机名。所以,如果你把8.8.8.8放在google dns服务器的名字里。你正在寻找的方法是:getHostEntry
来自微软的例子是:
public static void DoGetHostEntry(string hostname)
{
IPHostEntry host;
host = Dns.GetHostEntry(hostname);
Console.WriteLine("GetHostEntry({0}) returns:", hostname);
foreach (IPAddress ip in host.AddressList)
{
Console.WriteLine(" {0}", ip);
}
}
答
的一个好方法已经调查这将是为你单步执行代码在调试器中看到你实际上是传递给Dns.GetHostAddresses()
方法。
这样做,你会看到电话Convert.ToString(urlTextbox)
将返回一个类似于“System.Windows.Controls.TextBox:www.Google.com”的字符串。正如你所看到的,这几乎不是有效的主机名。您遇到DNS错误并不令人意外。 :)
请改为尝试Dns.GetHostAddresses(urlTextbox.Text)
。
有问题的代码不使用'GetHostByAddress'。如果OP只需要IP地址,那么'GetHostAddresses'方法(正在使用_is_)可以正常工作,至少在用有效主机名称调用时。 :) – 2014-11-02 19:07:48