Solved

Help Converting small app from VB6 to C#

Posted on 2008-10-29
2
934 Views
Last Modified: 2013-12-17
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

0
Comment
Question by:MiSheps
2 Comments
 
LVL 3

Expert Comment

by:Blackninja2007
ID: 22840258
0
 

Accepted Solution

by:
MiSheps earned 0 total points
ID: 22858908
Thanks for the link BlackNinja,

The only problem with the code in that link is that it assums that the computer in question has obtained it's IP through DHCP, and not through dialup. I am no expert on the matter myself by any means, but from what I read through research, this is not the best way to get the IP information because of that fact. In my case, I think it would work fine, becuase my adapters will always have DHCP, but I managed to find the following code to use which is a little more robust for doing the job.

Thank you for trying to help though. Your link helped give me more ideas to search on.







                //##################################################################
                // Get list of IP's
                // create collection to hold network interfaces
                {
                    dataGridView1.Rows.Clear();
                    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                    foreach (NetworkInterface adapter in nics)
                    {
                        IPAddress ipLocal = (adapter.GetIPProperties().UnicastAddresses != null && adapter.GetIPProperties().UnicastAddresses.Count > 0 ? adapter.GetIPProperties().UnicastAddresses[0].Address : null);
                        
                        if (ipLocal == null)
                        {
                            ipLocal = IPAddress.Parse("0.0.0.0");
                        }
                        string[] mac = { ipLocal.ToString(), adapter.Description, adapter.NetworkInterfaceType.ToString(), adapter.GetPhysicalAddress().ToString() };
                        dataGridView1.Rows.Add(mac);
 
                        for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                        {
                            this.dataGridView1.AutoResizeRow(i);
                        }
                    }

Open in new window

0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Flash (http://en.wikipedia.org/wiki/Adobe_Flash) has evolved over the years to where it has become a masterful tool for displaying content screen.  It has excellent layout placement, UI precision as well as rendering capabilities. This, along with t…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question