1

我让我的 Netduino Plus 2 使用 Web 服务来查找我希望它在我的项目中使用的一些值。我让 Netduino 检查的值之一是它的首选 IP 地址。如果 Netduino 的 IPAddress 与首选 IPAddress 不同,我想更改它。

我的项目中有一个名为 BindIPAddress(如下)的方法,它接受一个字符串。

对于无效参数,我收到一个代码为 10022 的 SocketException。当我调用 this.Socket.Bind 时会发生这种情况。我的班级有一个名为 Socket 的属性来保存 Socket 值。是因为我的套接字已经有一个端点吗?我尝试添加 this.Socket = null 然后 this.Socket = new (....... 认为我们需要一个新的套接字来使用,但这返回了相同的错误。

请告知如何将我的 IP 地址从一个静态 IP 地址更改为另一个。

 public void BindIPAddress(string strIPAddress)
    {
        try
        {

                Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].EnableStaticIP(strIPAddress, "255.255.240.0", "10.0.0.1");
            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].EnableStaticDns(new string[] { "10.0.0.2", "10.0.0.3" });
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse(strIPAddress), 80);


            this.Socket.Bind(ep);
            this.IpAddress = strIPAddress;
        }
        catch(SocketException exc)
        {
            Debug.Print(exc.Message);
            Debug.Print(exc.ErrorCode.ToString());


        }
        catch(Exception ex)
        {
            Debug.Print(ex.Message);



        }
        //Debug.Print(ep.Address.ToString());
    }
4

1 回答 1

2

这个问题可能有两种可能的解决方案。第一个是,您可以按照您尝试的方式以编程方式设置首选 IP 地址,第二个是,您可以使用MFDeploy工具,它附带 .NET Micro Framework SDK 捆绑包,允许您设置嵌入式在运行应用程序之前静态配置设备网络。

1)由于您没有提供其余代码,因此这是将套接字绑定EndPoint到的正确方法(实际上,我不会像您在此处发布的那样设计该类和绑定函数,而只是想强调缺少的部分你的代码):

    public void BindIPAddress(string strIPAddr)
    {
        Socket sock = null;
        IPEndPoint ipe = null;
        NetworkInterface[] ni = null;

        try
        {
            ipe = new IPEndPoint(IPAddress.Parse(strIPAddr), 80);
            sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);    // Assuming the WebService is connection oriented (TCP)
            // sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // if it broadcasts UDP packets, use this line (UDP)
            ni = NetworkInterface.GetAllNetworkInterfaces();

            if (ni != null && ni.Length > 0)
            {
                ni[0].EnableStaticIP(strIPAddr, "255.255.240.0", "10.0.0.1");
                ni[0].EnableStaticDns(new string[2] { "10.0.0.2", "10.0.0.3" });
                sock.Bind(ipe);
                this.Socket = sock;
                this.IpAddress = strIPAddr;
            }
            else
                throw new Exception("Network interface could not be retrieved successfully!");
        }
        catch(Exception ex)
        {
            Debug.Print(ex.Message);
        }
    }

2) 或无需编程,只需使用MFDeploy工具,您可以在将嵌入式设备插入 PC 后,按照以下路径设置首选 IP 地址:

MFDeploy > 目标 > 配置 > 网络

然后输入首选 IP 地址。仅此而已。

于 2015-04-22T09:33:27.633 回答