Title: Monitor de Red Windows Form
Course: 2025 - LISI - Redes Avanzadas 3-3 > Section: Redes Definidas por Software (SDN)

Imports MySql.Data.MySqlClient

Imports System.Net

Imports System.Net.NetworkInformation

Imports System.Net.Sockets

Public Class Form1

    Dim Adaptador As New MySqlDataAdapter

    Dim Datos As New DataSet

    Dim Conexion As New MySqlConnection

    Dim Registra As New MySqlCommand

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Try

            ' Conexión a la base de datos

            Conexion.ConnectionString = "server=148.227.3.236;user=reporte_red;password=reporte_red;database=reporte_red"

            Conexion.Open()

            ' Obtener nombre del host

            Dim hostname As String = Dns.GetHostName()

            ' Obtener IP con salida a Internet

            Dim ipAddress As String = GetLocalIPAddress()

            ' Obtener MAC address

            Dim macAddress As String = NetworkInterface.GetAllNetworkInterfaces() _

                .Where(Function(nic) nic.OperationalStatus = OperationalStatus.Up AndAlso

                                      nic.NetworkInterfaceType <> NetworkInterfaceType.Loopback) _

                .Select(Function(nic) BitConverter.ToString(nic.GetPhysicalAddress().GetAddressBytes())) _

                .FirstOrDefault()

            ' Fecha actual

            Dim fechaRegistro As String = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

            ' Preparar comando SQL

            Registra.Connection = Conexion

            Registra.CommandText = "INSERT INTO Carlos_equipo (hostname, macaddress, ip, fecha_registro) VALUES (@hostname, @mac, @ip, @fecha)"

            Registra.Parameters.Clear()

            Registra.Parameters.AddWithValue("@hostname", hostname)

            Registra.Parameters.AddWithValue("@mac", macAddress)

            Registra.Parameters.AddWithValue("@ip", ipAddress)

            Registra.Parameters.AddWithValue("@fecha", fechaRegistro)

            Registra.ExecuteNonQuery()

            MsgBox("Datos registrados correctamente.")

        Catch ex As Exception

            MsgBox("Error: " & ex.Message)

        End Try

    End Sub

    Private Function GetLocalIPAddress() As String

        Try

            Using socket As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)

                socket.Connect("8.8.8.8", 65530)

                Dim endPoint As IPEndPoint = CType(socket.LocalEndPoint, IPEndPoint)

                Return endPoint.Address.ToString()

            End Using

        Catch ex As Exception

            Return "IP no disponible"

        End Try

    End Function

End Class