【问题标题】:How to change IP Address using these code?如何使用这些代码更改 IP 地址?
【发布时间】:2013-04-21 00:11:06
【问题描述】:

我正在使用此代码更改 IP 地址、子网掩码和默认网关,但似乎只有默认网关更改,而 IP 地址和子网掩码没有。你能帮我么?我正在使用 Windows 7

Dim IPAddress As String = "192.168.2.130"
Dim SubnetMask As String = "255.0.0.0"
Dim Gateway As String = "192.168.2.1"
Dim objMC As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim objMOC As ManagementObjectCollection = objMC.GetInstances()

For Each objMO As ManagementObject In objMOC
    If (Not CBool(objMO("IPEnabled"))) Then
        Continue For
    End If

    Try
        Dim objNewIP As ManagementBaseObject = Nothing
        Dim objSetIP As ManagementBaseObject = Nothing
        Dim objNewGate As ManagementBaseObject = Nothing
        objNewIP = objMO.GetMethodParameters("EnableStatic")
        objNewGate = objMO.GetMethodParameters("SetGateways")

        'Set DefaultGateway
        objNewGate("DefaultIPGateway") = New String() {Gateway}
        objNewGate("GatewayCostMetric") = New Integer() {1}

        'Set IPAddress and Subnet Mask
        objNewIP("IPAddress") = New String() {IPAddress}
        objNewIP("SubnetMask") = New String() {SubnetMask}
        objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, Nothing)
        objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, Nothing)

        MessageBox.Show("Updated IPAddress, SubnetMask and Default Gateway!")
    Catch ex As Exception
        MessageBox.Show("Unable to Set IP : " & ex.Message)
    End Try
Next objMO

【问题讨论】:

    标签: vb.net static-ip-address


    【解决方案1】:

    右键单击 bin 中的 exe 并以管理员身份运行,因为更改 IP 地址需要管理员权限,而在 Windows 7 中,您必须以管理员身份运行才能拥有这种权限。

    【讨论】:

    • 作为评论会更好。如果您想让它成为答案,那么如果您解释了为什么以管理员身份运行 exe 会解决问题,那将是一个更好的答案。
    • 谢谢@Tim。我正在使用我的 ipad 回答,所以这意味着我可以写的字符数越少越好。我正在根据您的要求编辑我的答案。再次感谢。
    • 没问题。感谢您编辑并为答案添加更多内容。我只是那些总是想知道事情原因的人之一......我很确定我小时候让我的父母发疯了:)另外,除了 OP 之外的其他人将来可能需要这个答案,并且了解更多细节几乎总是有帮助的。
    猜你喜欢
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 2020-06-12
    • 2011-06-09
    • 2018-01-18
    • 1970-01-01
    相关资源
    最近更新 更多