gpt4 book ai didi

c# - 如何使用微框架正确更改静态 IP 地址?

转载 作者:行者123 更新时间:2023-12-03 12:00:00 25 4
gpt4 key购买 nike

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

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

对于无效参数,我收到一个代码为 10022 的 SocketException。当我调用 this.Socket.Bind 时会发生这种情况。我的类(class)有一个名为 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());
}

最佳答案

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

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

    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) 或无需编程,只需使用 MF部署工具,您可以在将嵌入式设备插入 PC 并按照以下路径设置首选 IP 地址:

MFDeploy > 目标 > 配置 > 网络

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

关于c# - 如何使用微框架正确更改静态 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29703919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com