【问题标题】:Convert String Array values to IP Addresses C#将字符串数组值转换为 IP 地址 C#
【发布时间】:2015-01-14 22:58:02
【问题描述】:

我正在处理一个小项目,但遇到了问题。我已经设置好了,因此用户可以将一系列 IP 地址粘贴到多行文本框中并 ping 每个 IP。我目前正在获取输入框中的每个值并将其添加到字符串数组中。我遇到的问题是使用 IPAddress.Parse 方法将该数组中的每个值转换为 IP。任何提示将不胜感激。它在 C# 中

using System;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Net;


namespace MultiPing
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }


    private void pingBtn_Click(object sender, EventArgs e)
    {
        try
        {
            int i;
            string[] allLines = inputBox.Text.Split('\n');
            Ping pingSender = new Ping();
            for (i = 0; i < allLines.Length; i++)
            {
                try
                {
                    IPAddress address = IPAddress.Parse(allLines[]);
                    PingReply reply = pingSender.Send(address);

                    if (reply.Status == IPStatus.Success)
                    {
                        outputBox.Text = address + " is up \n";
                    }
                    else
                    {
                        outputBox.Text = address + " is down \n";
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }


    }
}
}

【问题讨论】:

  • IPAddress address = IPAddress.Parse(allLines[]); allLines[i]?
  • 我试过了,但它给出了一个错误。我又试了一次,它随机开始工作....我现在感觉有点傻。
  • 提示:这不是随机的。可能如果你出错了,那是你的for 循环中的 1 个错误。不明白你为什么不在这里使用foreach
  • 我尝试了一个 foreach 看看它是否有所作为。我还在学习,所以我确实容易犯很多错误。最终我保留了 for 循环。

标签: c# arrays string


【解决方案1】:

改一下

IPAddress address = IPAddress.Parse(allLines[]);

IPAddress address = IPAddress.Parse(allLines[i]);

【讨论】:

  • 做到了。前不久它给出了一个错误。但现在它就像一个魅力。谢谢。
  • @Josh 可能如果你给它一个无效的 IP
  • 我检查了三次 IP 并将解析结果打印到控制台以确保它最终正确。这个问题已经解决,但现在我正在努力弄清楚为什么它实际上没有为它 ping 的每个 IP 添加一行
  • 您覆盖输出框文本而不是附加它。试试改成这个 --> outputBox.Text += address + " is up \n";
猜你喜欢
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
  • 2012-07-14
  • 2019-05-13
  • 2011-02-25
相关资源
最近更新 更多