绑定静态IP设置

时间:2017-07-12 16:04:09

标签: c# windows-ce tcp-ip

我正在尝试通过注册表配置设备的TCP / IP设置,但我似乎无法在没有软重启的情况下使其工作。

我一直在寻找谷歌的答案,并发现做到这一点的方法就是用来锁定DeviceIoControl()。

我看过注册表,他们肯定会改变我想要的,我不能让DeviceIoControl()返回除0之外的任何东西(失败),我不知道我做错了什么。

[DllImport("coredll.dll", EntryPoint = "CreateFile", SetLastError = true)]
private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFLagsAndAttributes, IntPtr hTemplateFile);
[DllImport("coredll.dll", EntryPoint = "DeviceIoControl", SetLastError = true)]
private static extern int DeviceIoControl(IntPtr hDevice, uint dwIoControlCode,  ref string lpInBuffer, int nInBufferSize, out string lpOutBuffer, int nOutBufferSize, ref int lpBytesReturned, IntPtr lpOverlapped);
[DllImport("coredll.dll", EntryPoint = "CloseHandle", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);

public static void SetTCPIP()
{
    RegistryKey baseKey = Registry.LocalMachine;
    string subKey = @"Comm\FEC1\Parms\TcpIp";
    string enableDhcpKey = "EnableDHCP";
    string gatewayKey = "DefaultGateway";
    string ipAddressKey = "IpAddress";
    string subnetMaskKey = "Subnetmask";
    string ipAddress = "192.168.8.100";
    string subnetMask = "255.255.255.0";
    string gateway = "192.168.8.1";

    WriteReg(baseKey, subKey, enableDhcpKey, 0);
    WriteRegMultiString(baseKey, subKey, ipAddressKey, ipAddress);
    WriteRegMultiString(baseKey, subKey, gatewayKey, gateway);
    WriteRegMultiString(baseKey, subKey, subnetMaskKey, subnetMask);
    CommitLocalMachineRegistry(); //RegFlushKey()
    BindAdapter();
}

private static void BindAdapter()
{
    const uint genericRead = 0x80000000;
    const uint genericWrite = 0x40000000;
    const int IOCTL_NDIS_REBIND_ADAPTER = 0x17002E;
    const int OPEN_EXISTING = 3;
    const string NI = @"NDS0:";
    //Open the Handle to Rebind the Network Adapter
    IntPtr hNdis = CreateFile(NI, genericRead | genericWrite, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
    if (hNdis == IntPtr.Zero)
    {
        Debug.WriteLine("!!!!!!!!!!!!!!!!!"+hNdis);
    }
    string Adapter = "FEC1\0";
    string OutBuffer = "";
    int bytesReturned = 0;
    //Rebind the Network Adapter
    int check = DeviceIoControl(hNdis, IOCTL_NDIS_REBIND_ADAPTER,  ref Adapter, Adapter.Length,
        out OutBuffer, 0, ref bytesReturned, IntPtr.Zero);

    if (check==0)
    {
        Debug.WriteLine("!!!!!!!!!!!!!!!!!!");
        Debug.WriteLine(Marshal.GetLastWin32Error());
    }
    //Close the Handle
    CloseHandle(hNdis);
}

我尝试使用GetLastWin32Error()获取有关此问题的更多信息,但它也返回0

编辑(无法添加评论) 我已经尝试过Adapter =“FEC1 \ 0 \ 0”而且我也试过编组作为一个没有运气的StringBuilder 编辑2 注册管理机构是基于HIVE的,因此重新启动后更改仍然存在。

0 个答案:

没有答案