【问题标题】:Set ipv6 for windows with C#使用 C# 为 Windows 设置 ipv6
【发布时间】:2012-08-23 08:15:09
【问题描述】:

我在 windows 中设置 Ipv6 时遇到问题。
以下代码可以设置 IPv4 地址,但我无法尝试设置 IPv6。
请帮帮我。

ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
try
{

    ManagementObjectCollection moc = mc.GetInstances();

    foreach (ManagementObject mo in moc)
    {
        // Make sure this is a IP enabled device. Not something like memory card or VM Ware
        if ((bool)mo["IPEnabled"])
        {
            if (mo["Caption"].Equals(nicName))
            {
                ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");
                ManagementBaseObject newGate = mo.GetMethodParameters("SetGateways");
                ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");

                newGate["DefaultIPGateway"] = new string[] { Gateway };
                newGate["GatewayCostMetric"] = new int[] { 1 };

                newIP["IPAddress"] = IpAddresses.Split(',');
                newIP["SubnetMask"] = new string[] { SubnetMask };

                newDNS["DNSServerSearchOrder"] = DnsSearchOrder.Split(',');

                ManagementBaseObject setIP = mo.InvokeMethod("EnableStatic", newIP, null);
                ManagementBaseObject setGateways = mo.InvokeMethod("SetGateways", newGate, null);
                ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);

                break;
            }
        }
    }
}
catch (Exception ex)
{
    string str = ex.Message;

}

【问题讨论】:

    标签: c# windows ipv6


    【解决方案1】:

    我也尝试通过 WMI 设置一个固定的 IPv6 地址,但它似乎不起作用(IPv4 地址确实起作用)。
    我发现这样做的唯一方法是从代码中启动 netsh,并使用它来设置固定(静态)IPv6 地址。如果有人有更优雅的解决方案,我会很乐意使用它。同时:

    使用 .NET System.Diagnostics.Process 类启动 netsh 进程。

    告诉你需要的参数的netsh命令参考是here.

    我发现我需要为我发送的每个命令启动一个新的 netsh 进程。
    对于每个 netsh 进程,我为进程的 OutputDataReceived 事件创建了一个处理程序,用于记录 netsh 反馈。

    【讨论】:

    • 是的,我认为“Link Local IPv6”是由MAC地址分配的,我们可以添加更多但不能更改。
    • 您是否尝试过对 IPHLPAPI.DLL 方法 SetUnicastIpAddressEntry 使用 P/Invoke?我没有必要尝试它,但它看起来很有希望满足您的需求。
    猜你喜欢
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多