Link to home
Start Free TrialLog in
Avatar of MiSheps
MiShepsFlag for United States of America

asked on

Help Converting small app from VB6 to C#

Greetings Experts!

I have a small portion of one of my vb6 programs that I want to convert to C# so I can continue to learn C#. (I learn best by studying live examples)

This program:
1) Gets a list of Network Cards on the computer
2) Lists the IP address assigned to each card
3) Gives the ability to release and renew the selected IP or card.

I would REALLY appreciate if a C# expert out there could take this as a fun conversion project and let me know how to do the same in C# so that I can learn.

I have uploaded the example project to: http://www.mishepsbasement.com/IPandAdapterInfo.rar

Thanks!

'################
'## In Form1 ####
'################
 
Option Explicit
 
Private Sub Form_Load()
    displayAdatersInfo
End Sub
 
Private Sub Command1_Click()
    IPRelease List2.ListIndex
    IPRelease List3.ListIndex
    displayAdatersInfo
End Sub
 
Private Sub Command2_Click()
    IPRenew List2.ListIndex
    IPRenew List3.ListIndex
    displayAdatersInfo
End Sub
 
'################
'## Module ######
'################
 
Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright ©1996-2008 VBnet, Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce
'               or publish this code on any web site,
'               online service, or distribute as source
'               on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Const MAX_ADAPTER_DESCRIPTION_LENGTH As Long = 128
Public Const MAX_ADAPTER_NAME As Long = 128
Public Const MAX_ADAPTER_NAME_LENGTH As Long = 256
Public Const MAX_ADAPTER_ADDRESS_LENGTH As Long = 8
Public Const MAX_HOSTNAME_LEN As Long = 128
Public Const MAX_DOMAIN_NAME_LEN As Long = 128
Public Const MAX_SCOPE_ID_LEN As Long = 256
 
Public Const ERROR_BUFFER_OVERFLOW As Long = 111
Public Const ERROR_INSUFFICIENT_BUFFER As Long = 122
Public Const GMEM_FIXED As Long = &H0
 
Public Const LB_SETTABSTOPS As Long = &H192
 
Public Const IP_SUCCESS As Long = 0
Public Const ERROR_SUCCESS As Long = 0
 
Private Const MAX_WSADescription As Long = 256
Private Const MAX_WSASYSStatus As Long = 128
Private Const WS_VERSION_REQD As Long = &H101
 
Private Type WSADATA
   wVersion As Integer
   wHighVersion As Integer
   szDescription(0 To MAX_WSADescription) As Byte
   szSystemStatus(0 To MAX_WSASYSStatus) As Byte
   wMaxSockets As Integer
   wMaxUDPDG As Integer
   dwVendorInfo As Long
End Type
 
Private Type IP_ADDRESS_STRING
    IpAddr(0 To 15)  As Byte
End Type
 
Private Type IP_MASK_STRING
    IpMask(0 To 15)  As Byte
End Type
 
Private Type IP_ADDR_STRING
    dwNext     As Long
    IpAddress  As IP_ADDRESS_STRING
    IpMask     As IP_MASK_STRING
    dwContext  As Long
End Type
 
Public Type IP_ADAPTER_INFO
  dwNext                As Long
  ComboIndex            As Long  'reserved
  sAdapterName(0 To (MAX_ADAPTER_NAME_LENGTH + 3))        As Byte
  sDescription(0 To (MAX_ADAPTER_DESCRIPTION_LENGTH + 3)) As Byte
  dwAddressLength       As Long
  sIPAddress(0 To (MAX_ADAPTER_ADDRESS_LENGTH - 1))       As Byte
  dwIndex               As Long
  uType                 As Long
  uDhcpEnabled          As Long
  CurrentIpAddress      As Long
  IpAddressList         As IP_ADDR_STRING
  GatewayList           As IP_ADDR_STRING
  DhcpServer            As IP_ADDR_STRING
  bHaveWins             As Long
  PrimaryWinsServer     As IP_ADDR_STRING
  SecondaryWinsServer   As IP_ADDR_STRING
  LeaseObtained         As Long
  LeaseExpires          As Long
End Type
 
Private Type IP_ADAPTER_INDEX_MAP
   Index As Long
   AdapterName(0 To MAX_ADAPTER_NAME - 1) As Integer
End Type
 
Private Type IP_INTERFACE_INFO
   NumAdapters As Long
   Adapter As IP_ADAPTER_INDEX_MAP
End Type
 
Public Declare Function GetAdaptersInfo Lib "iphlpapi.dll" _
   (IpAdapterInfo As Any, _
   pOutBufLen As Long) As Long
   
Private Declare Function GetInterfaceInfo Lib "iphlpapi.dll" _
  (ByVal pIfTable As Long, _
   dwOutBufLen As Long) As Long
 
Private Declare Function IPReleaseAddress Lib "iphlpapi.dll" _
   Alias "IpReleaseAddress" _
  (AdapterInfo As IP_ADAPTER_INDEX_MAP) As Long
 
Private Declare Function IPRenewAddress Lib "iphlpapi.dll" _
   Alias "IpRenewAddress" _
  (AdapterInfo As IP_ADAPTER_INDEX_MAP) As Long
 
Private Declare Function GlobalAlloc Lib "kernel32" _
  (ByVal wFlags As Long, _
   ByVal dwBytes As Long) As Long
 
Private Declare Function GlobalFree Lib "kernel32" _
  (ByVal hMem As Long) As Long
 
Public Declare Sub CopyMemory Lib "kernel32" _
   Alias "RtlMoveMemory" _
  (Destination As Any, _
   Source As Any, _
   ByVal Length As Long)
 
Public Declare Function WSAStartup Lib "ws2_32.dll" _
  (ByVal wVR As Long, _
   lpWSAD As WSADATA) As Long
 
'Public Declare Function WSACleanup Lib "ws2_32.dll" () As Long
 
Public Declare Function SendMessage Lib "user32" _
   Alias "SendMessageA" _
  (ByVal hwnd As Long, _
   ByVal wMsg As Long, _
   ByVal wParam As Long, _
   lParam As Any) As Long
   
   Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
 
 
'Public Function SocketsInitializeIP() As Boolean
'   Dim WSAD As WSADATA
'
'   SocketsInitialize = WSAStartup(WS_VERSION_REQD, WSAD) = IP_SUCCESS
'
'End Function
 
 
'Public Sub SocketsCleanup()
'   If WSACleanup() <> 0 Then
'       MsgBox "Windows Sockets error occurred in Cleanup.", vbExclamation
'   End If
'
'End Sub
 
 
Public Function IPRelease(ByVal dwAdapterIndex As Long) As Boolean
 
  'api vars
   Dim bufptr        As Long
   Dim dwOutBufLen   As Long
   Dim ip_map        As IP_ADAPTER_INDEX_MAP
   
  'working vars
   Dim success       As Long
   Dim nStructSize   As Long
   Dim NumAdapters   As Long
   Dim cnt           As Long
 
  'call GetInterfaceInfo with a buffer
  'of 0 length to have the API return
  'the size needed
   success = GetInterfaceInfo(0, dwOutBufLen)
 
   If success <> 0 And _
      success = ERROR_INSUFFICIENT_BUFFER Then
   
     'allocate memory for the buffer
     'and call GetInterfaceInfo again,
     'passing the memory buffer
      bufptr = GlobalAlloc(GMEM_FIXED, dwOutBufLen)
      success = GetInterfaceInfo(bufptr, dwOutBufLen)
       
      If success = ERROR_SUCCESS Then
               
        'the first 4 bytes of the returned data
        'is a long holding the number of adapters
        'retrieved
         CopyMemory NumAdapters, ByVal bufptr, 4
         
        'set a variable to hold the size
        'of the ip_map struct
         nStructSize = LenB(ip_map)
         
        'if an adapter installed...
         If NumAdapters > 0 Then
         
           'loop through installed adapters...
            For cnt = 0 To NumAdapters - 1
               
              'Copy a block of data from the
              'buffer into the ip_map structure.
              'On subsequent calls, the buffer
              'data returned is offset by the
              'number of adapters read * the size
              'of 1 ip_map structure, plus 4 to
              'account for the numAdapters long
              'retrieved above.
               CopyMemory ip_map, _
                          ByVal bufptr + (nStructSize * cnt) + 4, _
                          nStructSize
               
              'compare the index to the value passed
               If ip_map.Index = dwAdapterIndex Then
                  
                 'release the IP and set the return
                 'value from this function to True if
                 'the API returned ERROR_SUCCESS (0)
                  IPRelease = IPReleaseAddress(ip_map) = ERROR_SUCCESS
                  
                  If success <> ERROR_SUCCESS Then
                      MsgBox "ReleaseIP error " & success & _
                             ", Err# is " & Err.LastDllError
                  End If
                  
               End If  'If ip_map.Index
            
            Next  'For cnt
         
         End If  'If NumAdapters
      End If  'If success = ERROR_SUCCESS
   End If  'If success <> 0
   
   GlobalFree bufptr
 
End Function
 
 
Public Function IPRenew(ByVal dwAdapterIndex As Long) As Boolean
 
  'api vars
   Dim bufptr        As Long
   Dim dwOutBufLen   As Long
   Dim ip_map        As IP_ADAPTER_INDEX_MAP
   
  'working vars
   Dim success       As Long
   Dim nStructSize   As Long
   Dim NumAdapters   As Long
   Dim cnt           As Long
 
  'call GetInterfaceInfo with a buffer
  'of 0 length to have the API return
  'the size needed
   success = GetInterfaceInfo(0, dwOutBufLen)
 
   If success <> 0 And _
      success = ERROR_INSUFFICIENT_BUFFER Then
   
     'allocate memory for the buffer
     'and call GetInterfaceInfo again,
     'passing the memory buffer
      bufptr = GlobalAlloc(GMEM_FIXED, dwOutBufLen)
      success = GetInterfaceInfo(bufptr, dwOutBufLen)
       
      If success = ERROR_SUCCESS Then
               
        'the first 4 bytes of the returned data
        'is a long holding the number of adapters
        'retrieved
         CopyMemory NumAdapters, ByVal bufptr, 4
         
        'set a variable to hold the size
        'of the ip_map struct
         nStructSize = LenB(ip_map)
         
        'if an adapter installed...
         If NumAdapters > 0 Then
         
           'loop through the adapters...
            For cnt = 0 To NumAdapters - 1
               
              'Copy a block of data from the
              'buffer into the ip_map structure.
              'On subsequent calls, the buffer
              'data returned is offset by the
              'number of adapters read * the size
              'of 1 ip_map structure, plus 4 to
              'account for the numAdapters long
              'retrieved above.
               CopyMemory ip_map, _
                          ByVal bufptr + (nStructSize * cnt) + 4, _
                          nStructSize
               
              'compare the index to the value passed
               If ip_map.Index = dwAdapterIndex Then
                  
                 'renew the IP and set the return
                 'value from this function to True if
                 'the API returned ERROR_SUCCESS (0)
                  IPRenew = IPRenewAddress(ip_map) = ERROR_SUCCESS
                  
                  If success <> ERROR_SUCCESS Then
                      MsgBox "IpRenewAddress error " & success & _
                             ", Err# is " & Err.LastDllError
                  End If
                  
               End If  'If ip_map.Index
            
            Next  'For cnt
         
         End If  'If NumAdapters
      End If  'If success = ERROR_SUCCESS
   End If  'If success <> 0
   
   GlobalFree bufptr
 
End Function
 
 
Public Function displayAdatersInfo()
 
  'populates two listboxes with adapter info
 
  'working vars
   Dim buff()      As Byte
   Dim cbRequired  As Long
   Dim Adapter     As IP_ADAPTER_INFO
   Dim ptr1        As Long
   
  'clear the lists
   Form1.List2.Clear
   Form1.List3.Clear
 
  'call GetAdaptersInfo with null as the
  'buffer to have the API return the needed
  'buffer size in cbRequired.
   Call GetAdaptersInfo(ByVal 0&, cbRequired)
 
   If cbRequired > 0 Then
   
      ReDim buff(0 To cbRequired - 1) As Byte
      
      If GetAdaptersInfo(buff(0), cbRequired) = ERROR_SUCCESS Then
   
         ptr1 = VarPtr(buff(0))
         
        'ptr1 is 0 when no more adapters
         Do While (ptr1 <> 0)
         
           'copy the pointer to the first adapter
           'into the IP_ADAPTER_INFO type
            CopyMemory Adapter, ByVal ptr1, LenB(Adapter)
         
            With Adapter
         
              'The only thing we need to use
              'release/renew is the Adapter.dwIndex
              'value, added to list2. Data in list3
              'is purely for show, and is not
              'required to release or renew.
               Form1.List2.AddItem .dwIndex
               Form1.List3.AddItem TrimNull(StrConv(.IpAddressList.IpAddress.IpAddr, vbUnicode)) _
                             & vbTab & _
                             TrimNull(StrConv(.sDescription, vbUnicode))
               
               ptr1 = .dwNext
               
            End With  'With Adapter
            
         Loop  'Do While (ptr1 <> 0)
         
      End If
   End If
 
End Function
 
 
Public Function TrimNull(item As String)
 
    Dim pos As Integer
   
   'double check that there is a chr$(0) in the string
    pos = InStr(item, Chr$(0))
    If pos Then
       TrimNull = Left$(item, pos - 1)
    Else
       TrimNull = item
    End If
  
End Function

Open in new window

Avatar of Blackninja2007
Blackninja2007

ASKER CERTIFIED SOLUTION
Avatar of MiSheps
MiSheps
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial