【C#】获取指定网段主机名和IP地址小工具

最近玩树莓派经常发现找不到它的IP地址,每次都需要进路由器查看。如果不是在自己家的路由器更是没辙。于是想到能否做一个小工具,挨个ping一个网段内指定的地址段,如果能ping通就获取其主机名,然后显示。这样随便在哪里只要知道网段然后就能获取树莓派的IP了。

下面是做的界面:

主机名查询工具

使用方法超级简单,只需要指定一个网段,然后需要ping的地址范围。然后点击开始就行。如果你还行设置一下超时时间,也是可以滴。

主要代码也很简单,如下:

try
{
    int startIP = int.Parse(this.textBoxIPStart.Text.Trim());
    int endIP = int.Parse(this.textBoxIPEnd.Text.Trim());
    int timeOut = int.Parse(this.textBoxTimeOut.Text.Trim());
    this.richTextBoxOutput.Text = "";
    for (int i = startIP; i < endIP + 1; i++)
    {
        try
        {
            string currentIP = this.textBoxIP.Text.Trim() + i.ToString();
            this.labelStatus.Text = "正在ping " + currentIP;
            Ping pingSender = new Ping();
            //Ping 选项设置  
            PingOptions options = new PingOptions();
            options.DontFragment = true;
            //测试数据  
            string data = "get hostname";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            //设置超时时间  
            int timeout = timeOut;
            //调用同步 send 方法发送数据,将返回结果保存至PingReply实例  
            PingReply reply = pingSender.Send(currentIP, timeout, buffer, options);
            if (reply.Status == IPStatus.Success)
            {
                string responseIP = reply.Address.ToString();
                IPHostEntry myscanhost = Dns.GetHostByAddress(reply.Address.ToString());
                this.richTextBoxOutput.AppendText("响应的主机IP:" + responseIP + "       主机名:" + myscanhost.HostName.ToString());
                this.richTextBoxOutput.AppendText("\n");

            }
        }
        catch (Exception ex)
        {
            this.richTextBoxOutput.AppendText(ex.Message);
            this.richTextBoxOutput.AppendText("\n");
        }
    }
    this.richTextBoxOutput.AppendText("完成");
    this.labelStatus.Text = "完成";
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
    this.richTextBoxOutput.AppendText("\n");
}
}

顺便把工程文件也传上来吧,VS 2012编译通过:

GetHostName

此条目发表在作品, 应用程序分类目录。将固定链接加入收藏夹。

发表评论