Cambiare indirizzo Ip a runtime


Viaggiando con il mio portatile da casa all’ufficio mi trovo nella spiacevole condizione di reimpostare l’indirizzo Ip ogni volta che cambio postazione. Ho cercato pezzi di codice e alla fine sono giunto a questa conclusione:

Il cuore di tutto è la funzione setIp

Private Sub SetIP(ByVal IPAddress As String, ByVal SubnetMask As String, _
ByVal Gateway As String)

Dim managementClass As New ManagementClass(“Win32_NetworkAdapterConfiguration”)
Dim mgObjCollection As ManagementObjectCollection = managementClass.GetInstances()

For Each mgObject As ManagementObject In mgObjCollection
If Not CType(mgObject(“IPEnabled”), Boolean) Then Continue For

Try
Dim objNewIP As ManagementBaseObject = Nothing
Dim objSetIP As ManagementBaseObject = Nothing
Dim objNewGate As ManagementBaseObject = Nothing

objNewIP = mgObject.GetMethodParameters(“EnableStatic”)
objNewGate = mgObject.GetMethodParameters(“SetGateways”)

‘ Set the default gateway (decided to declare and initialise
‘ variables rather than attempting to initialize the array
‘ while communicating with the WMI.
Dim tmpStrArray() As String = {Gateway}

objNewGate(“DefaultIPGateway”) = tmpStrArray
Dim tmpIntArray() As Integer = {1}
objNewGate(“GatewayCostMetric”) = tmpIntArray

‘ Set the IP address and subnet.
tmpStrArray(0) = IPAddress
objNewIP(“IPAddress”) = tmpStrArray
tmpStrArray(0) = SubnetMask
objNewIP(“SubnetMask”) = tmpStrArray

objSetIP = mgObject.InvokeMethod(“EnableStatic”, objNewIP, Nothing)
objSetIP = mgObject.InvokeMethod(“SetGateways”, objNewGate, Nothing)
Catch ex As Exception
MessageBox.Show(“An error occured: ” + ex.Message)
End Try
Next
End Sub

che viene chiamata con il comando:

SetIP(” 192.168.1.105″, “255.255.255.0”, “192.168.1.1”)

per poterla utilizzare è necessario importare il system.management
Imports System.Management

e referenziare nel progetto la system.management.dll

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s