Results 1 to 25 of 25

Thread: [RESOLVED] Changing IP address with VB

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Apr 2005
    Posts
    248

    Resolved [RESOLVED] Changing IP address with VB

    Hey all,

    I have a PC, and I want to be able to change the IP address easier than going to Network connections > Picking the connection > Properties > Changing IP every time. The IP address is static (It's a laptop that I'm using for configuring multiple Routers for my CCNA labs, I want to be able to change the IP address more efficiently!).

    Attatched is a "Front only" view of what I'm trying to do. The program will sit on the bottom corner of the screen and will let me change the IP just by intering it and hitting a button, or clicking a "Preset settings" button.

    The question is - is there code that I can put in VB that will actually change the IP address settings for that particular network adaptor? I'm running XP.

    Thanks for any advice!
    Attached Images Attached Images  
    Last edited by BubbleLife; Feb 12th, 2007 at 07:20 AM.

  2. #2
    Frenzied Member zynder's Avatar
    Join Date
    Nov 2006
    Location
    localhost
    Posts
    1,434

    Re: Changing IP address with VB


  3. #3
    PowerPoster
    Join Date
    May 2006
    Posts
    2,988

    Re: Changing IP address with VB

    using WMI..
    also see the attached app i made for another program ..
    i have a newer version cleaned up and in modules etc but not finished.

    VB Code:
    1. Private Sub Command1_Click()
    2.     Dim ret As String
    3.     ret = SetStaticIp("192.168.0.2", "255.255.255.0", "192.168.0.1")
    4.     Debug.Print ret
    5. End Sub
    6.  
    7. Public Function SetStaticIp(ByVal pIPAddress As String, _
    8.                             ByVal pSubnet As String, _
    9.                             ByVal pGateway As String, _
    10.                             Optional ByVal pDNS1 As String, _
    11.                             Optional ByVal pDNS2 As String) _
    12.                             As String
    13.                            
    14.     Dim objWMIService       As Object
    15.     Dim colNetAdapters      As Object
    16.     Dim objNetAdapter       As Object
    17.     Dim strSelect           As String
    18.     Dim strIPAddress        As String
    19.     Dim strSubnet           As String
    20.     Dim strGateway          As String
    21.     Dim strDns1             As String
    22.     Dim strDns2             As String
    23.     Dim varIPAddress        As Variant
    24.     Dim varSubnet           As Variant
    25.     Dim varGateway          As Variant
    26.     Dim varGatewaymetric    As Variant
    27.     Dim varDns              As Variant
    28.     Dim lngEnable           As Long
    29.     Dim lngGateways         As Long
    30.     Dim lngDns              As Long
    31.     Dim blnDns              As Boolean
    32.    
    33.     On Error GoTo Error_Handler
    34.  
    35.     blnDns = True
    36.     Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    37.     strSelect = "Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE"
    38.     Set colNetAdapters = objWMIService.ExecQuery(strSelect)
    39.    
    40.     strIPAddress = Trim$(pIPAddress)
    41.     strSubnet = Trim$(pSubnet)
    42.     strGateway = Trim$(pGateway)
    43.    
    44.     If Not IsMissing(pDNS1) Then
    45.         strDns1 = Trim$(pDNS1)
    46.     End If
    47.     If Not IsMissing(pDNS2) Then
    48.         strDns2 = Trim$(pDNS2)
    49.     End If
    50.    
    51.     varIPAddress = Array("" & strIPAddress & "")
    52.     varSubnet = Array("" & strSubnet & "")
    53.     varGateway = Array("" & strGateway & "")
    54.     varGatewaymetric = Array(1)
    55.    
    56.     If Len(strDns1) = 0 Then
    57.         If Len(strDns2) = 0 Then
    58.             blnDns = False
    59.             varDns = ""
    60.         Else
    61.             varDns = Array("" & strDns2 & "")
    62.         End If
    63.     Else
    64.         If Len(strDns2) = 0 Then
    65.             varDns = Array("" & strDns1 & "")
    66.         Else
    67.             varDns = Array("" & strDns1 & "", "" & strDns2 & "")
    68.         End If
    69.     End If
    70.    
    71.     For Each objNetAdapter In colNetAdapters
    72.         lngEnable = objNetAdapter.EnableStatic(varIPAddress, varSubnet)
    73.         lngGateways = objNetAdapter.SetGateways(varGateway, varGatewaymetric)
    74.         If blnDns = True Then
    75.             lngDns = objNetAdapter.SetDNSServerSearchOrder(varDns)
    76.         Else
    77.             lngDns = objNetAdapter.SetDNSServerSearchOrder()
    78.         End If
    79.     Next
    80.    
    81.     If lngEnable > 1 Then
    82.         SetStaticIp = NetworkResults(lngEnable)
    83.     ElseIf lngGateways > 1 Then
    84.         SetStaticIp = NetworkResults(lngGateways)
    85.     ElseIf lngDns > 1 Then
    86.         If lngDns = 70 Then
    87.             SetStaticIp = "Invalid DNS Address"
    88.         Else
    89.             SetStaticIp = NetworkResults(lngDns)
    90.         End If
    91.     Else
    92.         SetStaticIp = NetworkResults(lngEnable)
    93.     End If
    94.    
    95. Error_Handler:
    96.     Set colNetAdapters = Nothing
    97.     Set objWMIService = Nothing
    98.     Set objNetAdapter = Nothing
    99.     If Err <> 0 Then _
    100.     SetStaticIp = "Error. " & Err.Description
    101. End Function
    102.  
    103. Public Function NetworkResults(ByVal pNumber As Integer)
    104.     Dim sResults As String
    105.     Select Case pNumber
    106.         Case 0: sResults = "Success, No Reboot Required"
    107.         Case 1: sResults = "Success, Reboot Required"
    108.         Case 64: sResults = "Method Not Supported"
    109.         Case 65: sResults = "Unknown Failure"
    110.         Case 66: sResults = "Invalid Subnet Mask"
    111.         Case 67: sResults = "Processing Error"
    112.         Case 68: sResults = "Invalid Input"
    113.         Case 69: sResults = "Gateways Limit Error"
    114.         Case 70: sResults = "Invalid IP address"
    115.         Case 71: sResults = "Invalid Gateway Address"
    116.         Case 72: sResults = "Registry Access Error"
    117.         Case 73: sResults = "Invalid Domain Name"
    118.         Case 74: sResults = "Invalid Host Name"
    119.         Case 75: sResults = "No WINS Server Defined"
    120.         Case 76: sResults = "Invalid File"
    121.         Case 77: sResults = "Invalid System Path"
    122.         Case 78: sResults = "File Copy Failed"
    123.         Case 79: sResults = "Invalid Security Parameter"
    124.         Case 80: sResults = "Unable to Configure TCP/IP"
    125.         Case 81: sResults = "Unable to Configure DHCP"
    126.         Case 82: sResults = "Unable to Renew DHCP"
    127.         Case 83: sResults = "Unable to Release DHCP"
    128.         Case 84: sResults = "IP Not Enabled On Adapter"
    129.         Case 85: sResults = "IPX Not Enabled On Adapter"
    130.         Case 86: sResults = "Frame/Network Error"
    131.         Case 87: sResults = "Invalid Frame Type"
    132.         Case 88: sResults = "Invalid Network Number"
    133.         Case 89: sResults = "Duplicate Network Number"
    134.         Case 90: sResults = "Parameter Out Of Bounds"
    135.         Case 91: sResults = "Access Denied"
    136.         Case 92: sResults = "Out Of Memory"
    137.         Case 93: sResults = "Already Exists"
    138.         Case 94: sResults = "Path, File, or Object Not Found"
    139.         Case 95: sResults = "Unable To Notify Service"
    140.         Case 96: sResults = "Unable To Notify DNS Service"
    141.         Case 97: sResults = "Interface Not Configurable"
    142.         Case 98: sResults = "Not All DHCP Released/Renewed"
    143.         Case 100: sResults = "DHCP Not Enabled On Adapter"
    144.     End Select
    145.     NetworkResults = sResults
    146. End Function
    Last edited by rory; Feb 12th, 2007 at 06:44 AM.

  4. #4
    PowerPoster
    Join Date
    May 2006
    Posts
    2,988

    Re: Changing IP address with VB

    and .. using the example zynder posted ..
    i created a modified version of that ...
    returns True or False. You could modify that, its just an example.

    You have to manually enter the adaptor name though.
    I didnt yet find code to enumerate through them, for XP that is.

    FORM:
    if entering DNS, enter multiple DNS servers with a comma (no spaces) between them
    VB Code:
    1. Private Sub Command1_Click()
    2.     Dim ret As String
    3.     ret = SetIPAddress(False, "192.168.0.2", "255.255.255.0", "192.168.0.1")
    4.     Debug.Print ret
    5. End Sub

    MODULE:
    VB Code:
    1. Option Explicit
    2.  
    3. Enum regTypes
    4.    ValNull = 0
    5.    ValString = 1
    6.    ValXString = 2
    7.    ValBinary = 3
    8.    ValDWord = 4
    9.    ValDWordLE = 4
    10.    ValDWordBE = 5
    11.    ValLink = 6
    12.    ValMultiString = 7
    13.    ValResList = 8
    14. End Enum
    15.  
    16. Private Type myBytes
    17.     B1 As Byte
    18.     B2 As Byte
    19.     B3 As Byte
    20.     B4 As Byte
    21. End Type
    22.  
    23. Private Type myLong
    24.     Val As Long
    25. End Type
    26.  
    27. Private Declare Function RegCreateKey Lib "advapi32.dll" Alias "RegCreateKeyA" _
    28. (ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As Long
    29.  
    30. Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long
    31.  
    32. Private Declare Function RegSetValueExString Lib "advapi32.dll" Alias "RegSetValueExA" _
    33. (ByVal hKey As Long, ByVal lpValueName As String, ByVal Reserved As Long, ByVal dwType As Long, _
    34. ByVal lpValue As String, ByVal cbData As Long) As Long
    35.  
    36. Private Declare Function RegSetValueExLong Lib "advapi32.dll" Alias "RegSetValueExA" _
    37. (ByVal hKey As Long, ByVal lpValueName As String, ByVal Reserved As Long, ByVal dwType As Long, _
    38. lpValue As Long, ByVal cbData As Long) As Long
    39.  
    40. Private Declare Function RegSetValueExByte Lib "advapi32" Alias "RegSetValueExA" _
    41. (ByVal hKey As Long, ByVal lpValueName As String, ByVal Reserved As Long, ByVal dwType As Long, _
    42. szData As Byte, ByVal cbData As Long) As Long
    43.  
    44. Private Declare Function SetAdapterIPAddress Lib "Iphlpapi" Alias "#135" _
    45. (ByVal szAdapterGUID As String, ByVal dwDHCP As Long, ByVal dwIP As Long, ByVal dwMask As Long, _
    46. ByVal dwGateway As Long) As Long
    47.  
    48. Public Function SetIPAddress(ByVal pDHCP As Boolean, _
    49.                             Optional ByVal pIPAddress As String, _
    50.                             Optional ByVal pSubnet As String, _
    51.                             Optional ByVal pGateway As String, _
    52.                             Optional ByVal pDNS As String) _
    53.                             As Boolean
    54.          
    55.     Dim strInterface    As String
    56.     Dim strIPAddress    As String
    57.     Dim strSubnet       As String
    58.     Dim strGateway      As String
    59.     Dim strDns          As String
    60.    
    61.     Const sVal As String = "SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\"
    62.    
    63.     On Error Resume Next
    64.        
    65.     strInterface = "{CE675518-5238-4C6D-8AD2-98B866B71CDF}"
    66.     If Len(strInterface) = 0 Then Exit Function
    67.    
    68.     strIPAddress = Trim$(pIPAddress)
    69.     strSubnet = Trim$(pSubnet)
    70.     strGateway = Trim$(pGateway)
    71.     If Not IsMissing(pDNS) Then
    72.         strDns = Trim$(pDNS)
    73.     End If
    74.    
    75.     If pDHCP = True Then
    76.         strIPAddress = vbNull
    77.         strSubnet = vbNull
    78.         strGateway = vbNull
    79.         SaveValue &H80000002, sVal & strInterface, "NameServer", "", ValString
    80.     Else
    81.         strIPAddress = IP2Long(strIPAddress)
    82.         strSubnet = IP2Long(strSubnet)
    83.         strGateway = IP2Long(strGateway)
    84.         SaveValue &H80000002, sVal & strInterface, "NameServer", strDns, ValString
    85.     End If
    86.    
    87.     SetIPAddress = SetAdapterIPAddress(strInterface, pDHCP, strIPAddress, strSubnet, strGateway) = 0
    88.  
    89. End Function
    90.  
    91. ' Convert a dotted quad IP string to a Long.
    92. Private Function IP2Long(IP As String) As Long
    93.     ' Perhaps the bytes are not in the politically correct order,
    94.     ' but as long as you undo it with Long2IP you'll be fine.
    95.     ReDim parse(0 To 3) As String
    96.     Dim B As myBytes
    97.     Dim L As myLong
    98.     parse = Split(IP, ".")
    99.     B.B1 = Val(parse(0))
    100.     B.B2 = Val(parse(1))
    101.     B.B3 = Val(parse(2))
    102.     B.B4 = Val(parse(3))
    103.     LSet L = B
    104.     IP2Long = L.Val
    105. End Function
    106.  
    107. Private Sub SaveValue(ByVal hKey As Long, ByVal strPath As String, _
    108.     ByVal strValue As String, ByVal varData As Variant, ByVal ValType As regTypes)
    109.     Dim keyhand As Long
    110.     Dim lResult As Long
    111.     Dim ordType As Long
    112.     Dim c       As Long
    113.     lResult = RegCreateKey(hKey, strPath, keyhand)
    114.     If lResult Then
    115.         'error
    116.     Else
    117.         Select Case ValType
    118.             Case ValBinary
    119.                 If (VarType(varData) = vbArray + vbByte) Then
    120.                     Dim ab() As Byte
    121.                     ab = varData
    122.                     c = UBound(ab) - LBound(ab) + 1
    123.                     lResult = RegSetValueExByte(keyhand, strValue, 0&, ValType, ab(0), c)
    124.                 Else
    125.                     'error
    126.                 End If
    127.             Case ValDWord, ValDWordBE, ValDWordLE
    128.                 If (VarType(varData) = vbInteger) Or (VarType(varData) = vbLong) Then
    129.                     Dim i As Long
    130.                     i = varData
    131.                     ordType = ValDWord
    132.                     lResult = RegSetValueExLong(keyhand, strValue, 0&, ordType, i, 4)
    133.                 Else
    134.                     'error
    135.                 End If
    136.             Case ValString, ValXString
    137.                 Dim s As String, iPos As Long
    138.                 s = varData
    139.                 ordType = ValString
    140.                 iPos = InStr(s, "%")
    141.                 If iPos Then
    142.                     If InStr(iPos + 2, s, "%") Then ordType = ValXString
    143.                 End If
    144.                 c = Len(s) + 1
    145.                 s = s & vbNullChar
    146.                 lResult = RegSetValueExString(keyhand, strValue, 0&, ordType, s, c)
    147.             Case Else
    148.                 'error
    149.         End Select
    150.         If lResult Then
    151.             'error
    152.         End If
    153.         RegCloseKey keyhand
    154.     End If
    155. End Sub
    Last edited by rory; Feb 12th, 2007 at 04:36 AM.

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Apr 2005
    Posts
    248

    Re: Changing IP address with VB

    Thank you for all your replies!

    I've been looking through the code, but I'm a bit of a VB noob I'm afraid and all the references to Reg keys and whatnot are losing me a bit.

    I don't need to edit the DNS settings, nor do I need to be able to change between static and dynamic IP.
    If it's not too much trouble, would someone be able to take one of these examples and strip out all the stuff about changing DNS settings and all the other bits? I just need something that calls the code, to go into my Command1, such as the example above, and a chunk of code that just changes the IP address, subnet mask, and default gateway.

    Thank you!

  6. #6
    PowerPoster
    Join Date
    May 2006
    Posts
    2,988

    Re: Changing IP address with VB

    Hi, both examples i posted change only the IP, Subnet, and Gateway.
    DNS is just an optional item in both of them.

    If you arent going to know the Adapter name, which I doubt you will if you are giving this to other people, then use the WMI one (1st one), for now at least. All you need is the one line inside the Command1_Click sub.

    SetStaticIp "192.168.0.2", "255.255.255.0", "192.168.0.1"

    The other 2 subs can go either in the same form or in a seperate module, doesnt matter. You can get the return string from the function by assigning it to a string variable, such as in the example. Or just set it like above.
    If you look at the attachment in the WMI post, you will also see there is more code for getting the IP information etc.

    However, typically you must also set the DNS info when using a Static IP or you wont get online.
    Last edited by rory; Feb 12th, 2007 at 06:26 AM.

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Apr 2005
    Posts
    248

    Re: Changing IP address with VB

    I don't mind setting the adaptor myself, the program is only for me at the moment anyway. What buttons/textboxes/etc are required for your second one though? Like I said, I'm new at this and the code all just turns into a blur to me when I read it, I only know very simple commands . I'm just trying to figure out which bits I can strip out relating to DNS settings and whatnot, but it's quite confusing for me.

  8. #8
    PowerPoster
    Join Date
    May 2006
    Posts
    2,988

    Re: Changing IP address with VB

    if you dont care about getting a return string from it ...
    and without the DNS info also ..

    VB Code:
    1. Private Sub Command1_Click()
    2.     SetIP "192.168.0.2", "255.255.255.0", "192.168.0.1"
    3. End Sub
    4.  
    5. Public Sub SetIP(ByVal pIPAddress As String, ByVal pSubnet As String, _
    6.                          ByVal pGateway As String)
    7.                            
    8.     Dim objWMIService       As Object
    9.     Dim colNetAdapters      As Object
    10.     Dim objNetAdapter       As Object
    11.     Dim strSelect           As String
    12.     Dim strIPAddress        As String
    13.     Dim strSubnet           As String
    14.     Dim strGateway          As String
    15.     Dim varIPAddress        As Variant
    16.     Dim varSubnet           As Variant
    17.     Dim varGateway          As Variant
    18.     Dim varGatewaymetric    As Variant
    19.    
    20.     On Error GoTo Error_Handler
    21.  
    22.     Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    23.     strSelect = "Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE"
    24.     Set colNetAdapters = objWMIService.ExecQuery(strSelect)
    25.    
    26.     strIPAddress = Trim$(pIPAddress)
    27.     strSubnet = Trim$(pSubnet)
    28.     strGateway = Trim$(pGateway)
    29.    
    30.     varIPAddress = Array("" & strIPAddress & "")
    31.     varSubnet = Array("" & strSubnet & "")
    32.     varGateway = Array("" & strGateway & "")
    33.     varGatewaymetric = Array(1)
    34.    
    35.     For Each objNetAdapter In colNetAdapters
    36.         objNetAdapter.EnableStatic varIPAddress, varSubnet
    37.         objNetAdapter.SetGateways varGateway, varGatewaymetric
    38.     Next
    39.    
    40. Error_Handler:
    41.     Set colNetAdapters = Nothing
    42.     Set objWMIService = Nothing
    43.     Set objNetAdapter = Nothing
    44. End Sub

  9. #9

    Thread Starter
    Addicted Member
    Join Date
    Apr 2005
    Posts
    248

    Re: Changing IP address with VB

    Oh thank you! That looks nice and simple .

    What is a return string? Does it need to return anything? It's setting data, not getting data. Like I said I'm only a noob at this. I don't know, do I want a return string? All I know is that I don't need to set DNS server settings, or change between static and dynamic IP .

    Thanks again ^^.

  10. #10
    PowerPoster
    Join Date
    May 2006
    Posts
    2,988

    Re: Changing IP address with VB

    Quote Originally Posted by Arby
    I don't mind setting the adaptor myself, the program is only for me at the moment anyway. What buttons/textboxes/etc are required for your second one though? Like I said, I'm new at this and the code all just turns into a blur to me when I read it, I only know very simple commands . I'm just trying to figure out which bits I can strip out relating to DNS settings and whatnot, but it's quite confusing for me.
    or just use the app i attached and add / delete / modify the buttons ..
    all they do is call the procedures in the code .. you can alter them or create additional procedures with the preset info.

  11. #11
    PowerPoster
    Join Date
    May 2006
    Posts
    2,988

    Re: Changing IP address with VB

    Quote Originally Posted by Arby
    Oh thank you! That looks nice and simple .

    What is a return string? Does it need to return anything? It's setting data, not getting data. Like I said I'm only a noob at this. I don't know, do I want a return string? All I know is that I don't need to set DNS server settings, or change between static and dynamic IP .

    Thanks again ^^.
    incase it doesnt change the info or there is an error while doing so, like if the user enters an incorrect IP, Subnet, or Gateway .. but you need to know what the error returned means hence that extra "NetworkResults" function in the first one. So basically incase you want the user to be alerted that there was an error and what that error is, or if it completed successfully.

  12. #12

    Thread Starter
    Addicted Member
    Join Date
    Apr 2005
    Posts
    248

    Re: Changing IP address with VB

    How does it return it, as a msgbox?

    And if it would be possible, may I have the code with with the return code but without the DNS stuff? I believe it gets rid of a lot of the reg stuff then. I don't want to just put all the code in and delete buttons because

    A) It creates unnessecery code-bloat
    B) I wouldn't know which buttons should be "Set" of "Un-set" by default, and if, say, radio boxes go, and the program has to perform an IF check to see which box is ticked, won't it crash?
    C) It makes it hard for me to try and edit the code afterwards because I don't know what's going on, and
    D) I don't know what buttons/radio boxes / textboxes and etc to add to the form or what to call them!

    Thanks!

  13. #13
    PowerPoster
    Join Date
    May 2006
    Posts
    2,988

    Re: Changing IP address with VB

    it returns it as a string in the above example, then you can do what you like with the string. The actual return is a number, that function just converts it to english.

    If you only want to know True or False then I can post that code, without the DNS.

  14. #14
    PowerPoster
    Join Date
    May 2006
    Posts
    2,988

    Re: Changing IP address with VB

    without DNS, returns a string.

    VB Code:
    1. Option Explicit
    2.  
    3. Private Sub Command1_Click()
    4.     Dim ret As String
    5.     ret = SetIp("192.168.0.2", "255.255.255.0", "192.168.0.1")
    6.     Debug.Print ret
    7. End Sub
    8.  
    9. '// wmi set static ip address
    10. Public Function SetIp(ByVal pIPAddress As String, ByVal pSubnet As String, _
    11.                       ByVal pGateway As String) As String
    12.     Dim objWMIService       As Object
    13.     Dim colNetAdapters      As Object
    14.     Dim objNetAdapter       As Object
    15.     Dim strSelect           As String
    16.     Dim strIPAddress        As String
    17.     Dim strSubnet           As String
    18.     Dim strGateway          As String
    19.     Dim varIPAddress        As Variant
    20.     Dim varSubnet           As Variant
    21.     Dim varGateway          As Variant
    22.     Dim varGatewaymetric    As Variant
    23.     Dim lngEnable           As Long
    24.     Dim lngGateways         As Long
    25. On Error GoTo Error_Handler
    26.     '// connect and query
    27.     Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    28.     strSelect = "Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE"
    29.     Set colNetAdapters = objWMIService.ExecQuery(strSelect)
    30.     '// clean strings
    31.     strIPAddress = Trim$(pIPAddress)
    32.     strSubnet = Trim$(pSubnet)
    33.     strGateway = Trim$(pGateway)
    34.     '// create arrays
    35.     varIPAddress = Array("" & strIPAddress & "")
    36.     varSubnet = Array("" & strSubnet & "")
    37.     varGateway = Array("" & strGateway & "")
    38.     varGatewaymetric = Array(1)
    39.     '// loop through adaptor info
    40.     For Each objNetAdapter In colNetAdapters
    41.         lngEnable = objNetAdapter.EnableStatic(varIPAddress, varSubnet)
    42.         lngGateways = objNetAdapter.SetGateways(varGateway, varGatewaymetric)
    43.     Next
    44.     '// return codes
    45.     If lngEnable > 1 Then
    46.         SetIp = NetworkResults(lngEnable)
    47.     ElseIf lngGateways > 1 Then
    48.         SetIp = NetworkResults(lngGateways)
    49.     Else
    50.         SetIp = NetworkResults(lngEnable)
    51.     End If
    52. Error_Handler: '// cleanup
    53.     Set colNetAdapters = Nothing
    54.     Set objWMIService = Nothing
    55.     Set objNetAdapter = Nothing
    56.     If Err <> 0 Then _
    57.     SetIp = "Error. " & Err.Description
    58. End Function
    59.  
    60. '// convert return codes to strings
    61. Public Function NetworkResults(ByVal pNumber As Integer)
    62.     Dim sResults As String
    63.     Select Case pNumber
    64.         Case 0: sResults = "Success, No Reboot Required"
    65.         Case 1: sResults = "Success, Reboot Required"
    66.         Case 64: sResults = "Method Not Supported"
    67.         Case 65: sResults = "Unknown Failure"
    68.         Case 66: sResults = "Invalid Subnet Mask"
    69.         Case 67: sResults = "Processing Error"
    70.         Case 68: sResults = "Invalid Input"
    71.         Case 69: sResults = "Gateways Limit Error"
    72.         Case 70: sResults = "Invalid IP address"
    73.         Case 71: sResults = "Invalid Gateway Address"
    74.         Case 72: sResults = "Registry Access Error"
    75.         Case 73: sResults = "Invalid Domain Name"
    76.         Case 74: sResults = "Invalid Host Name"
    77.         Case 75: sResults = "No WINS Server Defined"
    78.         Case 76: sResults = "Invalid File"
    79.         Case 77: sResults = "Invalid System Path"
    80.         Case 78: sResults = "File Copy Failed"
    81.         Case 79: sResults = "Invalid Security Parameter"
    82.         Case 80: sResults = "Unable to Configure TCP/IP"
    83.         Case 81: sResults = "Unable to Configure DHCP"
    84.         Case 82: sResults = "Unable to Renew DHCP"
    85.         Case 83: sResults = "Unable to Release DHCP"
    86.         Case 84: sResults = "IP Not Enabled On Adapter"
    87.         Case 85: sResults = "IPX Not Enabled On Adapter"
    88.         Case 86: sResults = "Frame/Network Error"
    89.         Case 87: sResults = "Invalid Frame Type"
    90.         Case 88: sResults = "Invalid Network Number"
    91.         Case 89: sResults = "Duplicate Network Number"
    92.         Case 90: sResults = "Parameter Out Of Bounds"
    93.         Case 91: sResults = "Access Denied"
    94.         Case 92: sResults = "Out Of Memory"
    95.         Case 93: sResults = "Already Exists"
    96.         Case 94: sResults = "Path, File, or Object Not Found"
    97.         Case 95: sResults = "Unable To Notify Service"
    98.         Case 96: sResults = "Unable To Notify DNS Service"
    99.         Case 97: sResults = "Interface Not Configurable"
    100.         Case 98: sResults = "Not All DHCP Released/Renewed"
    101.         Case 100: sResults = "DHCP Not Enabled On Adapter"
    102.     End Select
    103.     NetworkResults = sResults
    104. End Function

  15. #15
    PowerPoster
    Join Date
    May 2006
    Posts
    2,988

    Re: Changing IP address with VB

    without DNS, just returns True or False (True if successful without error)

    VB Code:
    1. Option Explicit
    2.  
    3. Private Sub Command1_Click()
    4.     Dim ret As Boolean
    5.     ret = SetIp("192.168.0.2", "255.255.255.0", "192.168.0.1")
    6.     Debug.Print ret
    7. End Sub
    8.  
    9. '// wmi set static ip address
    10. Public Function SetIp(ByVal pIPAddress As String, ByVal pSubnet As String, _
    11.                       ByVal pGateway As String) As Boolean
    12.     Dim objWMIService       As Object
    13.     Dim colNetAdapters      As Object
    14.     Dim objNetAdapter       As Object
    15.     Dim strSelect           As String
    16.     Dim strIPAddress        As String
    17.     Dim strSubnet           As String
    18.     Dim strGateway          As String
    19.     Dim varIPAddress        As Variant
    20.     Dim varSubnet           As Variant
    21.     Dim varGateway          As Variant
    22.     Dim varGatewaymetric    As Variant
    23.     Dim lngEnable           As Long
    24.     Dim lngGateways         As Long
    25. On Error GoTo Error_Handler
    26.     '// connect and query
    27.     Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    28.     strSelect = "Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE"
    29.     Set colNetAdapters = objWMIService.ExecQuery(strSelect)
    30.     '// clean strings
    31.     strIPAddress = Trim$(pIPAddress)
    32.     strSubnet = Trim$(pSubnet)
    33.     strGateway = Trim$(pGateway)
    34.     '// create arrays
    35.     varIPAddress = Array("" & strIPAddress & "")
    36.     varSubnet = Array("" & strSubnet & "")
    37.     varGateway = Array("" & strGateway & "")
    38.     varGatewaymetric = Array(1)
    39.     '// loop through adaptor info
    40.     For Each objNetAdapter In colNetAdapters
    41.         lngEnable = objNetAdapter.EnableStatic(varIPAddress, varSubnet)
    42.         lngGateways = objNetAdapter.SetGateways(varGateway, varGatewaymetric)
    43.     Next
    44.     If lngEnable = 0 And lngGateways = 0 Then SetIp = True
    45. Error_Handler: '// cleanup
    46.     Set colNetAdapters = Nothing
    47.     Set objWMIService = Nothing
    48.     Set objNetAdapter = Nothing
    49. End Function

  16. #16

    Thread Starter
    Addicted Member
    Join Date
    Apr 2005
    Posts
    248

    Re: Changing IP address with VB

    Wow that's great, thanks a lot! I'll have a look through it all and see what I can do.

    Thanks again!

  17. #17

    Thread Starter
    Addicted Member
    Join Date
    Apr 2005
    Posts
    248

    Re: [RESOLVED] Changing IP address with VB

    Oh, one last quick question - is there a bit of code for reading the IP - i.e, so I can have a button to "load current settings", or a text label to show the current settings? Thanks!

  18. #18
    PowerPoster
    Join Date
    May 2006
    Posts
    2,988

    Re: [RESOLVED] Changing IP address with VB

    no prob .. also you can reference WMI in the project using Microsoft WMI scripting Library, or just set them as object as in the above examples ..

    here is how to get the info, in this example i put the return values in the function as byref but you could just assign them to your text boxes direct.
    It returns false if there is an error, true if no error.
    I put textbox and WMI reference options in comments

    VB Code:
    1. Private Sub Command1_Click()
    2.     Dim sIP As String, sMask As String, sGate As String
    3.     If GetIPInfo(sIP, sMask, sGate) = True Then
    4.         Debug.Print sIP         '// txtIP.Text = sIP
    5.         Debug.Print sMask       '// txtSubnet.Text = sMask
    6.         Debug.Print sGate       '// txtGateway.Text = sGate
    7.     Else
    8.         Debug.Print "Error!"    '// MsgBox "Error!"
    9.     End If
    10. End Sub
    11.  
    12. '// wmi get ip info
    13. Public Function GetIPInfo(ByRef strIPAddress As String, _
    14.     ByRef strSubnet As String, ByRef strGateway As String) As Boolean
    15.     Dim WMIService  As Object   '// As SWbemServices
    16.     Dim IPConfigSet As Object   '// As SWbemObjectSet
    17.     Dim IPConfig    As Object   '// As SWbemObject
    18.     Dim SQL As String, i As Long
    19. On Error GoTo Error_Handler
    20.     '// connect and query
    21.     Set WMIService = GetObject("winmgmts:\\.\root\cimv2")
    22.     SQL = "Select IPAddress, IPSubnet, DNSServerSearchOrder, DefaultIPGateway, " & _
    23.           "DHCPEnabled from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE"
    24.     Set IPConfigSet = WMIService.ExecQuery(SQL)
    25.     '// loop through info
    26.     For Each IPConfig In IPConfigSet
    27.         '// get ip address
    28.         If Not IsNull(IPConfig.IpAddress) Then
    29.             For i = LBound(IPConfig.IpAddress) To UBound(IPConfig.IpAddress)
    30.                 strIPAddress = IPConfig.IpAddress(i)
    31.                 '// txtIP.Text = sIP
    32.             Next i
    33.         End If
    34.         '// get subnet mask
    35.         If Not IsNull(IPConfig.IPSubnet) Then
    36.             For i = LBound(IPConfig.IPSubnet) To UBound(IPConfig.IPSubnet)
    37.                 strSubnet = IPConfig.IPSubnet(i)
    38.                 '// txtSubnet.Text = sMask
    39.             Next i
    40.         End If
    41.         '// get gateway
    42.         If Not IsNull(IPConfig.DefaultIPGateway) Then
    43.             For i = LBound(IPConfig.DefaultIPGateway) To UBound(IPConfig.DefaultIPGateway)
    44.                 strGateway = IPConfig.DefaultIPGateway(i)
    45.                 '// txtGateway.Text = sGate
    46.             Next i
    47.         End If
    48.     Next IPConfig
    49. Error_Handler: '// cleanup
    50.     Set IPConfigSet = Nothing
    51.     Set WMIService = Nothing
    52.     GetIPInfo = Err.Number = 0
    53. End Function
    Last edited by rory; Feb 12th, 2007 at 07:54 AM.

  19. #19

    Thread Starter
    Addicted Member
    Join Date
    Apr 2005
    Posts
    248

    Re: Changing IP address with VB

    Ooh thank you!
    Thanks for all the help!
    Last edited by BubbleLife; Feb 12th, 2007 at 08:19 AM.

  20. #20
    PowerPoster
    Join Date
    May 2006
    Posts
    2,988

    Re: Changing IP address with VB

    no, only in the post where it uses the registry, the second post i made.
    all this other code is WMI stuff and doesnt use the registry.
    The PC needs to have WMI installed, with XP should be no issues.

  21. #21

    Thread Starter
    Addicted Member
    Join Date
    Apr 2005
    Posts
    248

    Re: [RESOLVED] Changing IP address with VB

    Thank you so much again for helping me

    I doubt this will be of any use to anyone, I'm sure everyone here could make something much better and more easily, but I'd like to share the app anyway in case anyone can find it useful. Feel free to nick bits of the code (hell, most of the code in there for changing the IP was from rory ), or re-create it as you see fit ^^.
    Attached Files Attached Files

  22. #22
    PowerPoster
    Join Date
    Feb 2006
    Location
    East of NYC, USA
    Posts
    5,691

    Re: Changing IP address with VB

    Quote Originally Posted by rory
    You have to manually enter the adaptor name though.
    I didnt yet find code to enumerate through them, for XP that is.
    VB Code:
    1. Dim sAdapter As String
    2. Dim objWMIService As Object
    3. Dim colNetAdapters As Object
    4. Dim objNetAdapter As Object
    5.  
    6.   Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    7.   sAdapter = "Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE"
    8.   Set colNetAdapters = objWMIService.ExecQuery(sAdapter)
    9.   ' loop through adaptor info
    10.   For Each objNetAdapter In colNetAdapters
    11.     cmbAdapter.AddItem objNetAdapter.Caption
    12.   Next objNetAdapter
    13.   If cmbAdapter.ListCount > 0 Then
    14.     cmbAdapter.ListIndex = 0
    15.   Else
    16.     MsgBox "There doesn't appear to be any IP-enabled Network Adapter in this computer.", vbCritical, App.EXEName
    17.   End If
    18.  
    19. 'When selecting the adapter to set the IP on, just cycle through colNetAdapters, looking for the objNetAdapter.Caption that matches cmbAdapter.Text

    How about a snippet to set the adapter to dynamic? I can't seem to find that info.
    Last edited by Al42; Feb 12th, 2007 at 01:08 PM.
    The most difficult part of developing a program is understanding the problem.
    The second most difficult part is deciding how you're going to solve the problem.
    Actually writing the program (translating your solution into some computer language) is the easiest part.

    Please indent your code and use [HIGHLIGHT="VB"] [/HIGHLIGHT] tags around it to make it easier to read.

    Please Help Us To Save Ana

  23. #23
    PowerPoster
    Join Date
    May 2006
    Posts
    2,988

    Re: Changing IP address with VB

    Quote Originally Posted by Al42
    How about a snippet to set the adapter to dynamic? I can't seem to find that info.
    I was meaning using the registry or API :-)

    What do you mean by Dynamic in this case?
    If DHCP then here it is ..

    VB Code:
    1. Private Sub Command1_Click()
    2.     If SetDHCP = True Then
    3.         Debug.Print "DHCP Set Successfully"
    4.     End If
    5. End Sub
    6.  
    7. '// wmi set dhcp
    8. Public Function SetDHCP() As Boolean
    9.     Dim objWMIService As Object
    10.     Dim colNetAdapters As Object
    11.     Dim objNetAdapter As Object
    12.     Dim strSelect As String
    13.     Dim lngEnable As Long
    14.     Dim lngDns As Long
    15. On Error GoTo Error_Handler
    16.     '// connect and query
    17.     Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    18.     strSelect = "Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE"
    19.     Set colNetAdapters = objWMIService.ExecQuery(strSelect)
    20.     '// loop through adaptor info
    21.     For Each objNetAdapter In colNetAdapters
    22.         lngEnable = objNetAdapter.EnableDHCP()
    23.         lngDns = objNetAdapter.SetDNSServerSearchOrder()
    24.     Next
    25.     If lngEnable = 0 And lngDns = 0 Then SetDHCP = True
    26. Error_Handler: '// cleanup
    27.     Set colNetAdapters = Nothing
    28.     Set objWMIService = Nothing
    29.     Set objNetAdapter = Nothing
    30. End Function
    Last edited by rory; Feb 12th, 2007 at 03:51 PM.

  24. #24
    PowerPoster
    Join Date
    Feb 2006
    Location
    East of NYC, USA
    Posts
    5,691

    Re: [RESOLVED] Changing IP address with VB

    That's what I was looking for. Thanks. I haven't been able to find any extensive documentation on WMI.
    The most difficult part of developing a program is understanding the problem.
    The second most difficult part is deciding how you're going to solve the problem.
    Actually writing the program (translating your solution into some computer language) is the easiest part.

    Please indent your code and use [HIGHLIGHT="VB"] [/HIGHLIGHT] tags around it to make it easier to read.

    Please Help Us To Save Ana

  25. #25
    PowerPoster
    Join Date
    May 2006
    Posts
    2,988

    Re: [RESOLVED] Changing IP address with VB

    Quote Originally Posted by Al42
    That's what I was looking for. Thanks. I haven't been able to find any extensive documentation on WMI.
    You can download and install this from Microsoft, though it requires IE.
    http://www.microsoft.com/downloads/d...displaylang=en

    Lately ive just been using MSDN as it has most of that info there and its easier to copy past the properties and methods.
    http://msdn2.microsoft.com/en-us/library/aa389273.aspx

    If i cant find something there then i go back to the WMI tools for further info.

    Also, if there is anything in particular you cant find you can always search for "VBScript WMI" in google .. or browse the "Scripting Guys" section here:
    http://www.microsoft.com/technet/scr...a/hsgarch.mspx
    Last edited by rory; Feb 12th, 2007 at 08:10 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width