2013-04-21 143 views
0

我使用此代码来更改IP地址,子网掩码和默认网关,但它似乎只有默认网关更改,IP地址和子网掩码doesnt。你能帮我么?我使用Windows 7如何使用这些代码更改IP地址?

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 

回答

1

右击斌你的exe,以管理员身份运行,因为更改IP地址需要管理员权限,并在Windows 7中有这样的权利,你必须运行作为管理员。

+0

这将是更好的评论。如果你想让它成为答案,如果你解释为什么以管理员身份运行exe可以解决问题,这将是一个**更好的**答案。 – Tim 2013-04-21 02:45:02

+0

谢谢@Tim。我正在使用我的iPad进行应答,这意味着我可以写的字符数量越少越好。我正根据你的要求编辑我的答案。再次感谢。 – Edper 2013-04-21 03:02:51

+0

没问题。感谢您编辑并在答案中添加更多内容。我只是那些总是想知道事情原因的人之一......我敢肯定,当我还是个孩子的时候,我的父母开始疯狂:)另外,OP以外的人在将来可能需要这个答案,有更多的细节几乎总是有帮助的。 – Tim 2013-04-21 03:06:16