Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

See and Change your MAC Address in VB.NET

VB.NET form

  • Please log in to reply
7 replies to this topic

#1 MXTECH

MXTECH

    CC Regular

  • Just Joined
  • PipPipPip
  • 46 posts

Posted 26 September 2008 - 06:47 PM

Hey guys i was diggin around my olf projects and found a cool tool, so i thought i would share :)

You need the followinf objects in your form:

1.combolistbox named :combo_network
2.lable named:label_mactext
3.textbox named:mac_text
4.button named :bt_defaultmac
5.button named :bt_update


Private Sub FillNetworkAdapters()
        Dim mc As System.Management.ManagementClass
        Dim mo As ManagementObject
        mc = New ManagementClass("Win32_NetworkAdapterConfiguration")
        Dim moc As ManagementObjectCollection = mc.GetInstances()
        For Each mo In moc
            If mo.Item("IPEnabled") = True Then
                Dim strAdapter As String
                strAdapter = mo.Item("Caption").ToString().Substring(11)

                combo_network.Items.Add(strAdapter)
            End If
        Next
    End Sub
    Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        FillNetworkAdapters()

    End Sub

Private Function GetMACAddress(ByVal Adapter As String) As String
        Dim mc As System.Management.ManagementClass
        Dim mo As ManagementObject
        mc = New ManagementClass("Win32_NetworkAdapterConfiguration")
        Dim moc As ManagementObjectCollection = mc.GetInstances()
        For Each mo In moc
            If mo.Item("IPEnabled") = True Then
                Dim strAdapter As String
                strAdapter = mo.Item("Caption").ToString().Substring(11)
                If strAdapter = Adapter Then
                    Return mo.Item("MacAddress").ToString()
                End If
            End If
        Next
    End Function

Private Sub combo_network_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles combo_network.SelectedIndexChanged
        label_mactext.Text = GetMACAddress(combo_network.SelectedItem.ToString)
    End Sub
    Private Function DoPadding(ByVal x As String) As String
        Dim Ret As String
        Dim z As Integer

        Ret = x
        If Len(x) < 4 Then
            For z = 1 To 4 - Len(x)
                Ret = "0" & Ret
            Next
        End If

        Return Ret
    End Function

    Private Sub ShowRestart()
        Dim res As MsgBoxResult = MsgBox("Your MAC Address has been changed. In order to make the changes take effect, either restart your computer or enable and disable the changed Network Adapter.", MsgBoxStyle.Information)

       
    End Sub

Private Sub bt_update_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_update.Click
        If IsOkay = False Then
            Exit Sub
        End If
        Dim regKey As Microsoft.Win32.RegistryKey
        Dim Addr As String = GetRoot(combo_network.SelectedItem.ToString())
        regKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(Addr, True)

        regKey.SetValue("NetworkAddress", mac_text.Text.Replace(":", ""))
        ShowRestart()
    End Sub


Private Function GetRoot(ByVal Adapter As String) As String
        Dim regKey As Microsoft.Win32.RegistryKey
        Dim i As Integer = 0

        Do
            Dim Root As String = "SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\"
            Dim Last As String = DoPadding(i)
            regKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(Root & Last, True)

            Try
                Dim cAdapter As String = regKey.GetValue("DriverDesc").ToString()
                If cAdapter = Adapter Then
                    Return Root & Last
                End If
            Catch
                Exit Do
            End Try
            i += 1
        Loop


    End Function

Private Function IsOkay() As Boolean
        If mac_text.Text = "" Then
            MsgBox("You didn't enter a MAC Address", MsgBoxStyle.Critical)
            Return False
        End If

        Dim ed As String = mac_text.Text.Replace(":", "")

        If ed.Length <> 12 Then
            MsgBox("A MAC Address must have a length of 12", MsgBoxStyle.Critical)
            Return False
        End If

        Try
            If combo_network.SelectedItem.ToString = "" Then
                MsgBox("No Network Adapter selected", MsgBoxStyle.Critical)
                Return False
            End If
        Catch
            MsgBox("No Network Adapter selected", MsgBoxStyle.Critical)
            Return False
        End Try


        Dim noerror As Boolean = True
        Dim i As Integer
        For i = 0 To ed.Length - 1
            If IsHex(ed.Substring(i, 1)) = False Then
                MsgBox("MAC Address in wrong format", MsgBoxStyle.Critical)
                Return False
            End If
        Next

        Return True
    End Function

Private Function IsHex(ByVal l As String) As Boolean
        Dim table As String = "0123456789ABCDEF"
        Dim i As Integer
        For i = 0 To table.Length - 1
            If l = table.Substring(i, 1) Then
                Return True
            End If
        Next
        Return False
    End Function

Private Sub bt_defaultmac_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_defaultmac.Click
        If IsOkay() = False Then
            Exit Sub
        End If
        Dim regKey As Microsoft.Win32.RegistryKey
        Dim Addr As String = GetRoot(combo_network.SelectedItem.ToString())
        regKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(Addr, True)

        Try
            regKey.DeleteValue("NetworkAddress")
        Catch
            'Do NOTHING
        End Try
        ShowRestart()
    End Sub

  • 0

#2 mbshinde78

mbshinde78

    CC Newcomer

  • Just Joined
  • PipPip
  • 19 posts

Posted 01 October 2008 - 06:28 AM

Thanks for the code. you can also share this code on planetsourcecode if you want more people should take advantage of it.
  • 0

#3 DonPedro

DonPedro

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 09 July 2010 - 09:25 AM

Nice code!
When I try to write it down in MS VB 2010 Express it says that it can't find 'System.Management.ManagementClass', is there anything I need to import at the very top of the code?

Ps. I know this thread is old but I would like something like this in visual basic to learn from. :)
  • 0

#4 STING3R777

STING3R777

    CC Newcomer

  • Just Joined
  • PipPip
  • 17 posts
  • Programming Language:C#, (Visual) Basic, Visual Basic .NET, VBScript
  • Learning:C, C++, C#, (Visual) Basic

Posted 07 October 2010 - 02:09 AM

You need to add the Reference to your project, PROJECT -> ADD REFERENCE -> .NET -> System.Management
  • 1

#5 UDPError

UDPError

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 15 October 2010 - 05:08 AM

I was going to state I found a better method to do the registry looping I'd like to share it.
I didn't really look at the date of the published article but thought I'd contribute.

private string GetKeyRoot(string adptr)
        {
            
                string root = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\";

                using (RegistryKey rootKey  = Registry.LocalMachine.OpenSubKey(root ,true))
                {
                    foreach (string keyname in rootKey.GetSubKeyNames())
                    {
                        try
                        {
                            using (RegistryKey key = rootKey.OpenSubKey(keyname))
                            {
                                if (key.GetValue("DriverDesc").ToString() == adptr)
                                {
                                    return key.ToString().Replace("HKEY_LOCAL_MACHINE\\", "");

                                }
                                
                            }
                        }
                        catch
                        {
                            return null;
                        }         
                    }
                }
            return null;
        }

which is in C# but converted to VB .NET would be something like

Private Function GetKeyRoot(adptr As String) As String

	Dim root As String = "SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\"

	Using rootKey As RegistryKey = Registry.LocalMachine.OpenSubKey(root, True)
		For Each keyname As String In rootKey.GetSubKeyNames()
			Try
				Using key As RegistryKey = rootKey.OpenSubKey(keyname)
					If key.GetValue("DriverDesc").ToString() = adptr Then

						Return key.ToString().Replace("HKEY_LOCAL_MACHINE\", "")

					End If
				End Using
			Catch
				Return Nothing
			End Try
		Next
	End Using
	Return Nothing
End Sub

That way you can eliminate your Padding function.
I've also steered clear of using WMI too..
All in all I enjoyed the thread

Edited by UDPError, 15 October 2010 - 05:10 AM.
explained reason for alternate method

  • 0

#6 JayAlban

JayAlban

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 19 February 2013 - 02:00 AM

Is this working in wireless Adapter?


  • 0

#7 MikeScirocco

MikeScirocco

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 24 August 2013 - 06:55 PM

When I click either button I see this,

 

"Application attempted to perform an operation not allowed by the security policy. To grant this applicaiton the required permission, contact your system administrator, or use the Microsoft .NET Framework Configuration tool.

If you click Continue, the application will ignore this error and attempt to continue. If you click Quit, the application will close immediately.

Requested registry access is not allowed."

 

Can you give me a few pointers on how to configure my system to allow registry access?

 

Thanks,

Mike

 


  • 0

#8 MikeScirocco

MikeScirocco

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 24 August 2013 - 08:57 PM

Do I need to address the registry change permission issue this way?

 

http://msdn.microsof...4(v=vs.71).aspx

 

The RegistryPermission class, which is in the System.Security.Permission namespace, controls the ability to access registry variables. Registry variables should not be stored in memory locations where code without RegistryPermission can access them. Similarly, when granting permissions, grant the least privilege necessary to get the job done. For more information, see RegistryPermission and System.Security.Permissions. Registry permission access values are defined by the RegistryPermissionAccess enumeration. For more information, see RegistryPermissionAccess. The following table details its members.

Value Description AllAccess Create, read, and write access to registry variables. Create Create access to registry variables. NoAccess No access to registry variables. Read Read access to registry variables. Write Write access to registry variables.

"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\TestApp" RegistryPermissionAccess.Write Or RegistryPermissionAccess.Read

Note   If you need some combination of permissions, such as permitting read and write access while denying create access, you can combine them with a bitwise Or operation, as in this example:


  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download