如何使用Microframework正确更改静态IP地址?

时间:2015-04-17 15:50:23

标签: c# sockets microcontroller .net-micro-framework netduino

我有我的Netduino Plus 2去网络服务查找我希望它在我的项目中使用的一些值。我有Netduino检查的一个值是它的首选IP地址。如果Netduino具有与其首选的IP地址不同的IP地址,我想要更改它。

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

我收到一个SocketException,代码为10022,用于无效参数。当我调用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());
    }

1 个答案:

答案 0 :(得分:2)

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

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地址。这就是全部。