【问题标题】:Socket error when getting IP address from a URL从 URL 获取 IP 地址时出现套接字错误
【发布时间】:2014-11-02 18:38:57
【问题描述】:

我正在尝试从用户那里获取网站并获取用户输入的任何网站的 IP 地址。我有一个文本框,用户可以在其中输入任何网站。如果用户输入“www.Google.com”,那么该文本会转到System.Net.Dns.GetHostAddresses(Convert.ToString(urlTextbox)); 但是,当我运行它并测试程序时,它会给我一个未处理的套接字错误。没有找到这样的主机。 我能做些什么来解决这个问题?

这就是我想要的: 这是我的代码:

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#

【问题讨论】:

    标签: c# dns


    【解决方案1】:

    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);
        }
    }
    

    【讨论】:

    • 有问题的代码没有使用GetHostByAddress。如果 OP 只需要 IP 地址,则 GetHostAddresses 方法(正在使用 )可以正常工作,至少在使用有效主机名调用时是这样。 :)
    【解决方案2】:

    调查此问题的一个好方法是让您逐步执行代码以在调试器中查看您实际上传递给Dns.GetHostAddresses() 方法的内容。

    这样做,您会看到调用Convert.ToString(urlTextbox) 将返回一个类似于“System.Windows.Controls.TextBox: www.Google.com”的字符串。如您所见,这几乎不是一个有效的主机名。收到 DNS 错误也就不足为奇了。 :)

    请尝试Dns.GetHostAddresses(urlTextbox.Text)

    【讨论】:

      猜你喜欢
      • 2018-05-08
      • 2019-06-25
      • 2013-01-20
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多