无效的IP地址异常

时间:2013-11-05 19:15:53

标签: c# visual-studio-2010 ip-address ping

我正在开发一个小型的C#项目,但我在将字符串转换为IPAddress时遇到了一些麻烦。这是代码:

Ping pingeage = new Ping();
String ip = tabtempsoctets1[0] 
    + "." + tabtempsoctets1[1] 
    + "." + tabtempsoctets1[2] 
    + "." + tabtempsoctets1[3];
MessageBox.Show(ip);
IPAddress adresseTest = IPAddress.Parse(ip);
boxLogs.Text = adresseTest.ToString();
PingReply reponse = pingeage.Send(adresseTest,2000);

但VisualStudio引发异常,告诉我IpAddress不是IPAddress。 为什么? tabtempoctets1是一个字符串数组,我手动添加了"." 这里有什么不对?

3 个答案:

答案 0 :(得分:4)

可能是您有领先或尾随空格。否则它应该成功解析"127.1.1.1"尝试:

IPAddress adresseTest = IPAddress.Parse(ip.Trim());

您还可以尝试IPAddress.TryParse,在解析失败的情况下不会引发异常。像:

string str = "     127.1.1.1       ";
IPAddress a;
if (IPAddress.TryParse(str.Trim(), out a))
{
    //parsing succesful
}
else
{
    //invalid string
}

您也可以使用string.Join连接字符串,如:

string ip = string.Join(".", tabtempsoctets1);

答案 1 :(得分:0)

        string[] tabtempsoctets1 = new string[] { "127", "1", "1", "1" }; 

        Ping pingeage = new Ping();
        String ip = tabtempsoctets1[0]
            + "." + tabtempsoctets1[1]
            + "." + tabtempsoctets1[2]
            + "." + tabtempsoctets1[3];
        MessageBox.Show(ip);
        IPAddress adresseTest = IPAddress.Parse(ip);
       // boxLogs.Text = adresseTest.ToString();
        PingReply reponse = pingeage.Send(adresseTest, 2000);

         works for me

答案 2 :(得分:0)

正确设置字符串string[] tabtempsoctets1 = { "127", "1", "1", "1" };后,上面的代码似乎对我有效。

您可以尝试转换为字节数组以检查范围。

这是我在Win7 PC上成功使用的测试应用程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace IPAddressTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] tabtempsoctets1 = { "127", "1", "1", "1" };
        Ping pingeage = new Ping();
        //Ping pingeage = new Ping();
        String ip = tabtempsoctets1[0]
            + "." + tabtempsoctets1[1]
            + "." + tabtempsoctets1[2]
            + "." + tabtempsoctets1[3];
        Console.WriteLine(ip);
        IPAddress adresseTest = IPAddress.Parse(ip);
        Console.WriteLine(adresseTest.ToString());

        byte [] addressAsBytes = new byte[tabtempsoctets1.Length];
        for (int i = 0; i < tabtempsoctets1.Length; i++)
        {
            if (!byte.TryParse(tabtempsoctets1[i], out addressAsBytes[i]))
                Console.WriteLine(tabtempsoctets1[i] + " is not formated correctely");
        }
        IPAddress adresseTest2 = new IPAddress(addressAsBytes);
        Console.WriteLine(adresseTest2.ToString());
        PingReply reponse = pingeage.Send(adresseTest2, 2000);
        Console.WriteLine(reponse.Status.ToString());

        Console.ReadKey();
    }
}

} enter code here