Selaa lähdekoodia

feat(snmp): use LLDP MIB on SNMP switches for topology discovery (#1117)

SNMP-managed switches that speak LLDP now feed topology discovery via LLDP-MIB polling (lldpRemTable + mgmt addresses), single-device ports get named by the neighbor sysName when DHCP has no hostname, and the ports card lists only physical interfaces (no LAG/VLAN rows).

Closes #931
Closes #1115
Nacho 2 kuukautta sitten
vanhempi
sitoutus
526a2418eb

+ 7 - 0
.gitignore

@@ -47,3 +47,10 @@ web/node_modules/
 
 plans
 docs/premortem
+
+# Instancia local de pruebas (worktrees dev; #931 arrastró una llave privada
+# generada por la instancia a un commit: gitleaks la cazó en el PR #1117)
+local-data/
+local-server.log
+netpulse-local
+jar.txt

+ 21 - 0
server-go/internal/adapters/live.go

@@ -3346,6 +3346,14 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 		if len(all) == 1 {
 			mac := all[0]
 			lease, ok := leaseMap[mac]
+			// #931: un vecino LLDP en esta boca es el propio equipo
+			// anunciándose; su sysName/mgmt-ip son mejor identificación que
+			// la MAC pelada cuando no hay hostname DHCP ni alias.
+			lldpName, lldpMgmt := "", ""
+			if nb := lldpNeighborOnPort(p.lldp, netdev); nb != nil {
+				lldpName = nb.displayName()
+				lldpMgmt = nb.Mgmt
+			}
 			// MAC de virtualización (QEMU/KVM, Proxmox, VMware, Hyper-V):
 			// el equipo enchufado es el hypervisor; lo aprendido es una
 			// NIC virtual de una VM/CT (#291).
@@ -3371,12 +3379,18 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 					// su i18n (#1039); aquí viaja el nombre a pelo.
 					port.ConnectedTo = name
 					port.PeerKind = "curated"
+				} else if lldpName != "" {
+					// #931: sin nombre mejor, el equipo se anuncia por LLDP.
+					port.ConnectedTo = lldpName
+					port.PeerKind = "mac"
 				} else {
 					port.ConnectedTo = port.Label
 					port.PeerKind = "mac"
 				}
 				if lease, ok := leaseMap[mac]; ok && lease.IP != "" {
 					port.Detail = lease.IP
+				} else if lldpMgmt != "" && lldpName != "" {
+					port.Detail = lldpMgmt + " · LLDP"
 				}
 				enriched = append(enriched, port)
 				continue
@@ -3388,6 +3402,13 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 				port.ConnectedTo = lease.IP
 			case aliasByMac[mac] != "":
 				port.ConnectedTo = aliasByMac[mac]
+			case lldpName != "":
+				// #931: sin lease ni alias, el nombre anunciado por el
+				// propio equipo (LLDP sysName) es la mejor etiqueta.
+				port.ConnectedTo = lldpName
+				if lldpMgmt != "" {
+					port.Detail = lldpMgmt + " · LLDP"
+				}
 			default:
 				port.ConnectedTo = mac
 			}

+ 40 - 0
server-go/internal/adapters/snmp_live.go

@@ -99,6 +99,15 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 		l.recordSnmpSuccess(cfg)
 	}
 
+	// #931: vecinos LLDP del switch vía LLDP-MIB (mismo contrato que la
+	// sonda lldpd de los routers, #300). Alimenta routerPolled.lldp y con
+	// ello la fase LLDP-first de la topología (inferLldpLinks). Un switch
+	// sin LLDP devuelve (nil, nil) sin ruido; el error solo se loguea.
+	lldpRem, lldpErr := npsnmp.PollLldpRemTable(session)
+	if lldpErr != nil {
+		log.Printf("[netpulse] SNMP LLDP %s: %v", cfg.LogLabel(), lldpErr)
+	}
+
 	portIdxToName := map[int]string{}
 	for _, p := range ports {
 		portIdxToName[p.Index] = p.DisplayName()
@@ -178,6 +187,7 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 		ports:     ethPorts,
 		fdb:       fdbMap,
 		brMac:     brMac,
+		lldp:      snmpLldpNeighbors(lldpRem, portIdxToName),
 		polledAt:  now.UnixMilli(),
 	}
 	l.mu.Lock()
@@ -404,6 +414,36 @@ func snmpFdbMap(fdb []npsnmp.FdbEntry, portIdxToName map[int]string) map[string]
 	return out
 }
 
+// snmpLldpNeighbors convierte los vecinos LLDP-MIB del switch al contrato
+// LldpNeighbor (#931). El puerto se nombra como en el FDB (DisplayName del
+// ifTable vía ifIndex; fallback al número de puerto de bridge, paridad con
+// snmpFdbMap #661) para que inferLldpLinks case el vecino con las MACs
+// aprendidas en esa boca.
+func snmpLldpNeighbors(rem []npsnmp.LldpRemEntry, portIdxToName map[int]string) []LldpNeighbor {
+	if len(rem) == 0 {
+		return nil
+	}
+	out := make([]LldpNeighbor, 0, len(rem))
+	for _, e := range rem {
+		port := portIdxToName[e.IfIndex]
+		if port == "" {
+			port = portIdxToName[e.LocalPortNum]
+		}
+		if port == "" {
+			port = fmt.Sprintf("port-%d", e.LocalPortNum)
+		}
+		out = append(out, LldpNeighbor{
+			Port:       port,
+			ChassisMac: e.ChassisMac,
+			Chassis:    e.Chassis,
+			Mgmt:       e.Mgmt,
+			Caps:       e.Caps,
+			PortDesc:   e.PortDesc,
+		})
+	}
+	return out
+}
+
 // snmpAggregateNet suma la tasa (bps) de todos los puertos para dar una
 // métrica agregada al switch SNMP (#661). Devuelve nil si todo está a 0
 // (primera muestra sin delta o sin tráfico).

+ 121 - 0
server-go/internal/adapters/snmp_lldp_test.go

@@ -0,0 +1,121 @@
+package adapters
+
+import (
+	"context"
+	"reflect"
+	"testing"
+	"time"
+
+	npsnmp "github.com/gnacho/netpulse/server-go/internal/snmp"
+)
+
+// #931: la conversión LLDP-MIB → LldpNeighbor nombra el puerto como el FDB
+// (DisplayName del ifTable) para que inferLldpLinks case el vecino con las
+// MACs aprendidas; sin mapeo cae al bridgePort y a un nombre generado
+// (paridad con snmpFdbMap, #661).
+func TestSnmpLldpNeighborsNaming(t *testing.T) {
+	rem := []npsnmp.LldpRemEntry{
+		{LocalPortNum: 5, IfIndex: 5, ChassisMac: "78:55:36:02:58:BA", Chassis: "ryzen-ai", Mgmt: "192.168.1.80", Caps: []string{"Wlan"}, PortDesc: "enp195s0"},
+		// Sin DisplayName para el ifIndex: cae al LocalPortNum si tiene nombre.
+		{LocalPortNum: 7, IfIndex: 70, ChassisMac: "D8:EC:5E:60:C7:82", Chassis: "LGS310C-2"},
+		// Sin nombre en ninguno de los dos: nombre generado.
+		{LocalPortNum: 9, IfIndex: 90, Chassis: "otro"},
+	}
+	names := map[int]string{5: "Slot0/5", 7: "Slot0/7"}
+	got := snmpLldpNeighbors(rem, names)
+	if len(got) != 3 {
+		t.Fatalf("esperaba 3 vecinos, obtuve %d", len(got))
+	}
+	want0 := LldpNeighbor{Port: "Slot0/5", ChassisMac: "78:55:36:02:58:BA", Chassis: "ryzen-ai", Mgmt: "192.168.1.80", Caps: []string{"Wlan"}, PortDesc: "enp195s0"}
+	if !reflect.DeepEqual(got[0], want0) {
+		t.Fatalf("vecino 0 inesperado:\n got %+v\nwant %+v", got[0], want0)
+	}
+	if got[1].Port != "Slot0/7" {
+		t.Fatalf("vecino 1 puerto: %q, esperaba Slot0/7 (fallback a LocalPortNum)", got[1].Port)
+	}
+	if got[2].Port != "port-9" {
+		t.Fatalf("vecino 2 puerto: %q, esperaba port-9 (nombre generado)", got[2].Port)
+	}
+}
+
+func TestSnmpLldpNeighborsVacio(t *testing.T) {
+	if got := snmpLldpNeighbors(nil, map[int]string{5: "Slot0/5"}); got != nil {
+		t.Fatalf("sin vecinos debe devolver nil, obtuve %+v", got)
+	}
+}
+
+// #931: en una boca con UN solo equipo aprendido y sin hostname DHCP ni
+// alias, el sysName anunciado por LLDP es la mejor etiqueta (antes salía la
+// MAC o la label del puerto). La mgmt-ip viaja al detalle.
+func TestGetRouterDetailLldpNombraEquipoSolitario(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	cfg := RouterConfig{ID: "sw1", Name: "LGS310C", Host: "192.168.1.217", Type: "managed-switch", SnmpEnabled: true}
+	l.routers = []RouterConfig{cfg}
+	l.lastPolled["sw1"] = &routerPolled{
+		cfg: cfg,
+		ports: []EthPort{
+			{ID: "snmp-5", Label: "Slot0/5", Iface: "Slot0/5", Up: true, Snmp: true},
+			{ID: "snmp-6", Label: "Slot0/6", Iface: "Slot0/6", Up: true, Snmp: true},
+		},
+		fdb: map[string]string{
+			"78:55:36:02:58:BA": "Slot0/5",
+			"AA:BB:CC:DD:EE:FF": "Slot0/6",
+		},
+		lldp: []LldpNeighbor{
+			{Port: "Slot0/5", Chassis: "ryzen-ai", ChassisMac: "78:55:36:02:58:BA", Mgmt: "192.168.1.80", Caps: []string{"Wlan"}},
+		},
+		polledAt: time.Now().UnixMilli(),
+	}
+
+	det, err := l.GetRouterDetail(context.Background(), "sw1")
+	if err != nil || det == nil {
+		t.Fatalf("detalle: %v %v", det, err)
+	}
+	ports := map[string]EthPort{}
+	for _, p := range det.Ports {
+		ports[p.ID] = p
+	}
+	p5 := ports["snmp-5"]
+	if p5.ConnectedTo != "ryzen-ai" {
+		t.Fatalf("snmp-5 connectedTo: %q, esperaba ryzen-ai (LLDP sysName)", p5.ConnectedTo)
+	}
+	if p5.Detail != "192.168.1.80 · LLDP" {
+		t.Fatalf("snmp-5 detail: %q, esperaba mgmt-ip · LLDP", p5.Detail)
+	}
+	if p5.DeviceMac != "78:55:36:02:58:BA" {
+		t.Fatalf("snmp-5 deviceMac: %q", p5.DeviceMac)
+	}
+	// Puerto sin LLDP: comportamiento previo intacto (cae a la label).
+	p6 := ports["snmp-6"]
+	if p6.ConnectedTo != "Slot0/6" {
+		t.Fatalf("snmp-6 connectedTo: %q, esperaba Slot0/6 (sin LLDP, sin cambios)", p6.ConnectedTo)
+	}
+}
+
+// #931: un hostname DHCP sigue ganando al sysName LLDP (precedencia
+// lease > LLDP > MAC).
+func TestGetRouterDetailLldpNoPisaHostnameDhcp(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	cfg := RouterConfig{ID: "sw1", Name: "LGS310C", Host: "192.168.1.217", Type: "managed-switch", SnmpEnabled: true}
+	l.routers = []RouterConfig{cfg}
+	l.lastPolled["sw1"] = &routerPolled{
+		cfg: cfg,
+		ports: []EthPort{
+			{ID: "snmp-5", Label: "Slot0/5", Iface: "Slot0/5", Up: true, Snmp: true},
+		},
+		fdb:      map[string]string{"78:55:36:02:58:BA": "Slot0/5"},
+		lldp:     []LldpNeighbor{{Port: "Slot0/5", Chassis: "ryzen-ai", Mgmt: "192.168.1.80"}},
+		leases:   []DhcpLease{{MAC: "78:55:36:02:58:BA", Hostname: "ryzen9AI", IP: "192.168.1.80"}},
+		polledAt: time.Now().UnixMilli(),
+	}
+
+	det, err := l.GetRouterDetail(context.Background(), "sw1")
+	if err != nil || det == nil {
+		t.Fatalf("detalle: %v %v", det, err)
+	}
+	for _, p := range det.Ports {
+		if p.ID == "snmp-5" && p.ConnectedTo != "ryzen9AI" {
+			t.Fatalf("connectedTo: %q, esperaba ryzen9AI (hostname DHCP gana a LLDP)", p.ConnectedTo)
+		}
+	}
+}

+ 34 - 2
server-go/internal/snmp/ifTable.go

@@ -13,6 +13,7 @@ type PortStats struct {
 	Name       string
 	Descr      string
 	Alias      string
+	Type       int
 	SpeedBps   uint64
 	HighSpeedMbps uint32
 	OperUp     bool
@@ -62,7 +63,7 @@ func (p PortStats) DisplayName() string {
 
 func PollIfTable(s *gosnmp.GoSNMP) ([]PortStats, error) {
 	oids := []string{
-		OidIfIndex, OidIfDescr, OidIfSpeed, OidIfOperStatus,
+		OidIfIndex, OidIfDescr, OidIfType, OidIfSpeed, OidIfOperStatus,
 		OidIfInOctets, OidIfInErrors, OidIfOutOctets, OidIfOutErrors,
 		OidIfName, OidIfHighSpeed, OidIfAlias,
 	}
@@ -90,7 +91,36 @@ func PollIfTable(s *gosnmp.GoSNMP) ([]PortStats, error) {
 		out = append(out, *ps)
 	}
 	sortByIndex(out)
-	return out, nil
+	return physicalIfPorts(out), nil
+}
+
+// nonPhysicalIfTypes: ifTypes (IANA) que NO son una boca física del switch
+// y no deben aparecer en la tarjeta de puertos (#1115): interfaces LAG,
+// VLANs, loopbacks, bridges y túneles. Verificado en un Linksys LGS310C
+// real: po1-8 llegan como ieee8023adLag(161) y vlan1 como l3ipvlan(136).
+var nonPhysicalIfTypes = map[int]bool{
+	24:  true, // softwareLoopback
+	53:  true, // propVirtual
+	131: true, // tunnel
+	135: true, // l2vlan
+	136: true, // l3ipvlan
+	161: true, // ieee8023adLag
+	209: true, // bridge
+}
+
+// physicalIfPorts descarta las interfaces no físicas del ifTable (#1115).
+// Filtra por EXCLUSIÓN y no por "solo ethernetCsmacd": un switch que no
+// reporte ifType (Type=0 por walk fallido) conserva todos sus puertos en
+// lugar de quedarse a cero.
+func physicalIfPorts(ports []PortStats) []PortStats {
+	out := ports[:0]
+	for _, p := range ports {
+		if nonPhysicalIfTypes[p.Type] {
+			continue
+		}
+		out = append(out, p)
+	}
+	return out
 }
 
 func applyPortField(ps *PortStats, oid string, pdu gosnmp.SnmpPDU) {
@@ -99,6 +129,8 @@ func applyPortField(ps *PortStats, oid string, pdu gosnmp.SnmpPDU) {
 		ps.Index = int(uint64Val(pdu))
 	case OidIfDescr:
 		ps.Descr = stringVal(pdu)
+	case OidIfType:
+		ps.Type = int(uint64Val(pdu))
 	case OidIfSpeed:
 		ps.SpeedBps = uint64Val(pdu)
 	case OidIfOperStatus:

+ 234 - 0
server-go/internal/snmp/lldpRem.go

@@ -0,0 +1,234 @@
+// lldpRem.go — Vecinos LLDP vía LLDP-MIB (IEEE 802.1AB) en switches SNMP
+// (#931). El walk de lldpRemTable da, por cada vecino: chasis (MAC u otro
+// id), sysName, puerto remoto y capacidades; lldpRemManAddrTable da sus
+// IPs de gestión (están en el ÍNDICE, no en las columnas). El puerto local
+// (lldpRemLocalPortNum) se cruza con dot1dBasePortIfIndex para nombrarlo
+// como el FDB/ifTable y que la topología case el vecino con las MACs
+// aprendidas en esa boca (mismo contrato LldpNeighbor que lldpd, #300).
+package snmp
+
+import (
+	"fmt"
+	"strconv"
+	"strings"
+
+	"github.com/gosnmp/gosnmp"
+)
+
+// LldpRemEntry es un vecino LLDP anunciado en un puerto local del switch.
+// Todos los campos del anuncio son opcionales; vacío = no anunciado.
+type LldpRemEntry struct {
+	LocalPortNum int      // lldpRemLocalPortNum (puerto de bridge local)
+	IfIndex      int      // resuelto vía dot1dBasePortIfIndex (0 si no mapea)
+	ChassisMac   string   // MAYÚSCULAS si el id del chasis es MAC (subtype 4)
+	Chassis      string   // sysName si lo anuncia; si no, id del chasis no-MAC
+	Mgmt         string   // primera IPv4 de gestión anunciada para ese vecino
+	Caps         []string // capacidades enabled ("Bridge", "Router", "Wlan"...)
+	PortDesc     string   // descripción del puerto remoto (o su id si no hay)
+}
+
+// PollLldpRemTable sondea los vecinos LLDP del switch. Un equipo sin LLDP
+// (o con la tabla vacía) devuelve (nil, nil): la ausencia de vecinos no es
+// error y NO debe tumbar el poll SNMP. El error solo viaja cuando el propio
+// walk falla, para que el caller lo registre en el log de diagnosis.
+func PollLldpRemTable(s *gosnmp.GoSNMP) ([]LldpRemEntry, error) {
+	portToIfIndex := map[int]int{}
+	if pdus, err := walkSafe(s, OidDot1dBasePortIfIndex); err == nil {
+		for _, pdu := range pdus {
+			idx := trailingIndex(pdu.Name, OidDot1dBasePortIfIndex)
+			if idx <= 0 {
+				continue
+			}
+			portToIfIndex[idx] = int(uint64Val(pdu))
+		}
+	}
+
+	pdus, err := walkSafe(s, OidLldpRemTable)
+	if err != nil {
+		return nil, fmt.Errorf("snmp lldp walk: %w", err)
+	}
+	if len(pdus) == 0 {
+		return nil, nil
+	}
+
+	mgmt := map[string]string{}
+	if addrPdus, err := walkSafe(s, OidLldpRemManAddr); err == nil {
+		mgmt = lldpMgmtAddrs(addrPdus)
+	}
+
+	return lldpRemEntries(pdus, portToIfIndex, mgmt), nil
+}
+
+// lldpRemEntries convierte los PDUs crudos del walk lldpRemTable en
+// entradas. Es pura para probarla sin agente SNMP. El índice de cada PDU es
+// <columna>.<timeMark>.<localPortNum>.<remIndex>; las columnas 1-3 (los
+// componentes del índice) son not-accessible y normalmente no aparecen en
+// el walk, así que la primera columna visible suele ser la 4
+// (chassisIdSubtype). Como BulkWalkAll devuelve los OIDs ordenados, el
+// subtype siempre llega antes que su id dentro del mismo vecino.
+func lldpRemEntries(pdus []gosnmp.SnmpPDU, portToIfIndex map[int]int, mgmt map[string]string) []LldpRemEntry {
+	type remKey struct{ port, idx int }
+	byKey := map[remKey]*LldpRemEntry{}
+	var order []remKey
+	get := func(k remKey) *LldpRemEntry {
+		if e, ok := byKey[k]; ok {
+			return e
+		}
+		e := &LldpRemEntry{LocalPortNum: k.port}
+		byKey[k] = e
+		order = append(order, k)
+		return e
+	}
+
+	// Subtypes que necesita el parseo de los ids (llegan antes que el id).
+	chassisSubtype := map[remKey]int{}
+	portSubtype := map[remKey]int{}
+
+	for _, pdu := range pdus {
+		col, port, idx, ok := lldpRemColumn(pdu.Name)
+		if !ok {
+			continue
+		}
+		k := remKey{port, idx}
+		e := get(k)
+		switch col {
+		case 4: // lldpRemChassisIdSubtype
+			chassisSubtype[k] = int(uint64Val(pdu))
+		case 5: // lldpRemChassisId
+			if chassisSubtype[k] == 4 { // macAddress
+				e.ChassisMac = macFromOctets(octetsVal(pdu))
+			} else if s := stringVal(pdu); s != "" {
+				e.Chassis = s
+			}
+		case 6: // lldpRemPortIdSubtype
+			portSubtype[k] = int(uint64Val(pdu))
+		case 7: // lldpRemPortId (fallback de PortDesc si no hay descripción)
+			if portSubtype[k] == 3 { // macAddress
+				e.PortDesc = macFromOctets(octetsVal(pdu))
+			} else {
+				e.PortDesc = stringVal(pdu)
+			}
+		case 8: // lldpRemPortDesc (gana al id)
+			if s := stringVal(pdu); s != "" {
+				e.PortDesc = s
+			}
+		case 9: // lldpRemSysName (gana al id del chasis no-MAC)
+			if s := stringVal(pdu); s != "" {
+				e.Chassis = s
+			}
+		case 12: // lldpRemSysCapEnabled
+			e.Caps = lldpCapsFromBits(octetsVal(pdu))
+		}
+	}
+
+	out := make([]LldpRemEntry, 0, len(order))
+	for _, k := range order {
+		e := byKey[k]
+		e.IfIndex = portToIfIndex[k.port]
+		if e.IfIndex == 0 {
+			// Paridad con el FDB (#661): sin mapeo, cae al número de
+			// puerto de bridge (muchos switches lo usan como ifIndex).
+			e.IfIndex = k.port
+		}
+		e.Mgmt = mgmt[fmt.Sprintf("%d.%d", k.port, k.idx)]
+		out = append(out, *e)
+	}
+	return out
+}
+
+// lldpRemColumn extrae (columna, localPortNum, remIndex) del OID de una
+// PDU de lldpRemTable. Columnas válidas: 4-12 (las 1-3 son el índice).
+func lldpRemColumn(name string) (col, port, idx int, ok bool) {
+	parts := oidSuffixInts(name, OidLldpRemTable)
+	if len(parts) != 4 {
+		return 0, 0, 0, false
+	}
+	col, port, idx = parts[0], parts[2], parts[3]
+	if col < 4 || col > 12 || port <= 0 || idx <= 0 {
+		return 0, 0, 0, false
+	}
+	return col, port, idx, true
+}
+
+// lldpMgmtAddrs extrae la primera IPv4 de gestión por vecino
+// ("<localPort>.<remIndex>") de los PDUs de lldpRemManAddrTable. La
+// dirección viaja EN EL ÍNDICE: <columna>.<timeMark>.<port>.<remIndex>.
+// <addrSubtype>.<addrLen>.<addr...>; addrSubtype 1 = IPv4 (IANA family).
+// El resto de familias (IPv6 incluida) se ignoran: Mgmt es una sola IP y
+// la IPv4 es la útil para cruzar con la flota.
+func lldpMgmtAddrs(pdus []gosnmp.SnmpPDU) map[string]string {
+	out := map[string]string{}
+	for _, pdu := range pdus {
+		parts := oidSuffixInts(pdu.Name, OidLldpRemManAddr)
+		// col + timeMark + port + remIndex + subtype + len + addr
+		if len(parts) < 6+1 {
+			continue
+		}
+		port, remIndex := parts[2], parts[3]
+		subtype, addrLen := parts[4], parts[5]
+		if subtype != 1 || addrLen != 4 || len(parts) < 6+addrLen {
+			continue
+		}
+		key := fmt.Sprintf("%d.%d", port, remIndex)
+		if _, seen := out[key]; seen {
+			continue
+		}
+		out[key] = fmt.Sprintf("%d.%d.%d.%d", parts[6], parts[7], parts[8], parts[9])
+	}
+	return out
+}
+
+// oidSuffixInts devuelve los componentes numéricos del OID tras el prefijo
+// ("" si no cuelga de él). Defensivo: cualquier componente no entero
+// invalida el parseo.
+func oidSuffixInts(name, prefix string) []int {
+	if !strings.HasPrefix(name, prefix+".") {
+		return nil
+	}
+	suffix := name[len(prefix)+1:]
+	fields := strings.Split(suffix, ".")
+	out := make([]int, 0, len(fields))
+	for _, f := range fields {
+		n, err := strconv.Atoi(f)
+		if err != nil || n < 0 {
+			return nil
+		}
+		out = append(out, n)
+	}
+	return out
+}
+
+// octetsVal extrae los bytes crudos de una PDU (OctetString/Bits llegan
+// como []byte; algunos agentes los mandan como string).
+func octetsVal(v gosnmp.SnmpPDU) []byte {
+	switch val := v.Value.(type) {
+	case []byte:
+		return val
+	case string:
+		return []byte(val)
+	}
+	return nil
+}
+
+// macFromOctets formatea una MAC MAYÚSCULA canónica (#960) de 6 bytes
+// ("" si el dato no es usable).
+func macFromOctets(b []byte) string {
+	if len(b) < 6 {
+		return ""
+	}
+	return fmt.Sprintf("%02X:%02X:%02X:%02X:%02X:%02X", b[0], b[1], b[2], b[3], b[4], b[5])
+}
+
+// lldpCapsFromBits decodifica LldpSystemCapabilitiesMap (BITS, bit 0 = MSB
+// del primer octeto, IEEE 802.1AB). Nombres alineados con los que usa
+// lldpcli y el contrato del agente ("Bridge", "Router", "Wlan", "Station").
+func lldpCapsFromBits(b []byte) []string {
+	names := []string{"Other", "Repeater", "Bridge", "Wlan", "Router", "Telephone", "Docsis", "Station"}
+	var out []string
+	for bit := 0; bit < 8 && bit < len(b)*8; bit++ {
+		if b[bit/8]&(0x80>>uint(bit%8)) != 0 {
+			out = append(out, names[bit])
+		}
+	}
+	return out
+}

+ 171 - 0
server-go/internal/snmp/lldpRem_test.go

@@ -0,0 +1,171 @@
+package snmp
+
+import (
+	"reflect"
+	"testing"
+
+	"github.com/gosnmp/gosnmp"
+)
+
+// Fixture grabada del Linksys LGS310C real (3-Oct-2026, #931): un vecino
+// (PC con lldpd) en el puerto local 5. Los OIDs son los literales del
+// snmpwalk para que el test pinae el formato exacto del índice.
+func lgs310cRemPdus() []gosnmp.SnmpPDU {
+	const base = OidLldpRemTable
+	return []gosnmp.SnmpPDU{
+		{Name: base + ".4.9900.5.1", Type: gosnmp.Integer, Value: 4},                            // chassisIdSubtype = macAddress
+		{Name: base + ".5.9900.5.1", Type: gosnmp.OctetString, Value: []byte{0x78, 0x55, 0x36, 0x02, 0x58, 0xBA}},
+		{Name: base + ".6.9900.5.1", Type: gosnmp.Integer, Value: 3},                            // portIdSubtype = macAddress
+		{Name: base + ".7.9900.5.1", Type: gosnmp.OctetString, Value: []byte{0x78, 0x55, 0x36, 0x02, 0x58, 0xBA}},
+		{Name: base + ".8.9900.5.1", Type: gosnmp.OctetString, Value: []byte("enp195s0")},       // portDesc
+		{Name: base + ".9.9900.5.1", Type: gosnmp.OctetString, Value: []byte("ryzen-ai")},       // sysName
+		{Name: base + ".10.9900.5.1", Type: gosnmp.OctetString, Value: []byte("CachyOS Linux")}, // sysDesc (ignorado)
+		{Name: base + ".11.9900.5.1", Type: gosnmp.OctetString, Value: []byte{0x39, 0x00}},      // capsSupported
+		{Name: base + ".12.9900.5.1", Type: gosnmp.OctetString, Value: []byte{0x10, 0x00}},      // capsEnabled
+	}
+}
+
+// Fixture del lldpRemManAddrTable del mismo switch: IPv4 e IPv6 del vecino
+// (5.1), la dirección viaja en el índice.
+func lgs310cManAddrPdus() []gosnmp.SnmpPDU {
+	const base = OidLldpRemManAddr
+	return []gosnmp.SnmpPDU{
+		{Name: base + ".3.9900.5.1.1.4.192.168.1.80", Type: gosnmp.Integer, Value: 2},
+		{Name: base + ".3.9900.5.1.2.16.254.128.0.0.0.0.0.0.220.231.67.22.10.131.233.175", Type: gosnmp.Integer, Value: 2},
+		{Name: base + ".5.9900.5.1.1.4.192.168.1.80", Type: gosnmp.ObjectIdentifier, Value: ".0.0"},
+	}
+}
+
+func TestLldpRemEntriesLgs310c(t *testing.T) {
+	portMap := map[int]int{5: 5}
+	mgmt := lldpMgmtAddrs(lgs310cManAddrPdus())
+	got := lldpRemEntries(lgs310cRemPdus(), portMap, mgmt)
+	if len(got) != 1 {
+		t.Fatalf("esperaba 1 vecino, obtuve %d: %+v", len(got), got)
+	}
+	e := got[0]
+	want := LldpRemEntry{
+		LocalPortNum: 5,
+		IfIndex:      5,
+		ChassisMac:   "78:55:36:02:58:BA",
+		Chassis:      "ryzen-ai",
+		Mgmt:         "192.168.1.80",
+		Caps:         []string{"Wlan"},
+		PortDesc:     "enp195s0",
+	}
+	if !reflect.DeepEqual(e, want) {
+		t.Fatalf("vecino inesperado:\n got %+v\nwant %+v", e, want)
+	}
+}
+
+// Sin mapeo dot1dBasePortIfIndex: el IfIndex cae al número de puerto de
+// bridge (paridad con el FDB, #661).
+func TestLldpRemEntriesIfIndexFallback(t *testing.T) {
+	got := lldpRemEntries(lgs310cRemPdus(), map[int]int{7: 70}, nil)
+	if len(got) != 1 {
+		t.Fatalf("esperaba 1 vecino, obtuve %d", len(got))
+	}
+	if got[0].IfIndex != 5 {
+		t.Fatalf("IfIndex fallback: %d, esperaba 5", got[0].IfIndex)
+	}
+	if got[0].Mgmt != "" {
+		t.Fatalf("Mgmt sin tabla manaddr: %q, esperaba vacío", got[0].Mgmt)
+	}
+}
+
+// Chasis NO-MAC (subtype 7 = local) sin sysName: el id viaja a Chassis y
+// ChassisMac queda vacío; con sysName este gana al id.
+func TestLldpRemEntriesChassisNoMac(t *testing.T) {
+	const base = OidLldpRemTable
+	pdus := []gosnmp.SnmpPDU{
+		{Name: base + ".4.100.2.1", Type: gosnmp.Integer, Value: 7},
+		{Name: base + ".5.100.2.1", Type: gosnmp.OctetString, Value: []byte("switch-sotano")},
+	}
+	got := lldpRemEntries(pdus, nil, nil)
+	if len(got) != 1 {
+		t.Fatalf("esperaba 1 vecino, obtuve %d", len(got))
+	}
+	if got[0].Chassis != "switch-sotano" || got[0].ChassisMac != "" {
+		t.Fatalf("chasis inesperado: %+v", got[0])
+	}
+
+	pdus = append(pdus,
+		gosnmp.SnmpPDU{Name: base + ".9.100.2.1", Type: gosnmp.OctetString, Value: []byte("SW1.lan")},
+	)
+	got = lldpRemEntries(pdus, nil, nil)
+	if got[0].Chassis != "SW1.lan" {
+		t.Fatalf("sysName debe ganar al id: %+v", got[0])
+	}
+}
+
+// PDUs basura (OID de columna sin instancia, índices cortos/largos,
+// columnas fuera de rango, valores no enteros) no producen entradas ni
+// pánico.
+func TestLldpRemEntriesSkipsUnusablePdus(t *testing.T) {
+	const base = OidLldpRemTable
+	pdus := []gosnmp.SnmpPDU{
+		{Name: base, Type: gosnmp.Integer, Value: 4},
+		{Name: base + ".4.9900.5", Type: gosnmp.Integer, Value: 4},          // índice corto
+		{Name: base + ".4.9900.5.1.9", Type: gosnmp.Integer, Value: 4},      // índice largo
+		{Name: base + ".3.9900.5.1", Type: gosnmp.Integer, Value: 4},        // columna 3 (índice, not-accessible)
+		{Name: base + ".13.9900.5.1", Type: gosnmp.Integer, Value: 4},       // columna inexistente
+		{Name: base + ".4.9900.0.1", Type: gosnmp.Integer, Value: 4},        // puerto 0
+		{Name: base + ".4.9900.x.1", Type: gosnmp.Integer, Value: 4},        // componente no entero
+		{Name: ".1.0.8802.1.1.2.1.4.1.2.4.9900.5.1", Type: gosnmp.Integer, Value: 4}, // prefijo distinto
+	}
+	if got := lldpRemEntries(pdus, nil, nil); len(got) != 0 {
+		t.Fatalf("esperaba 0 entradas, obtuve %d: %+v", len(got), got)
+	}
+}
+
+// Dos vecinos en puertos distintos conservan orden y campos independientes.
+func TestLldpRemEntriesDosVecinos(t *testing.T) {
+	const base = OidLldpRemTable
+	pdus := []gosnmp.SnmpPDU{
+		{Name: base + ".4.9900.5.1", Type: gosnmp.Integer, Value: 4},
+		{Name: base + ".5.9900.5.1", Type: gosnmp.OctetString, Value: []byte{0x78, 0x55, 0x36, 0x02, 0x58, 0xBA}},
+		{Name: base + ".9.9900.5.1", Type: gosnmp.OctetString, Value: []byte("ryzen-ai")},
+		{Name: base + ".4.9900.8.1", Type: gosnmp.Integer, Value: 4},
+		{Name: base + ".5.9900.8.1", Type: gosnmp.OctetString, Value: []byte{0xD8, 0xEC, 0x5E, 0x60, 0xC7, 0x82}},
+		{Name: base + ".9.9900.8.1", Type: gosnmp.OctetString, Value: []byte("LGS310C-2")},
+	}
+	got := lldpRemEntries(pdus, map[int]int{5: 5, 8: 8}, nil)
+	if len(got) != 2 {
+		t.Fatalf("esperaba 2 vecinos, obtuve %d", len(got))
+	}
+	if got[0].LocalPortNum != 5 || got[0].Chassis != "ryzen-ai" {
+		t.Fatalf("vecino 0 inesperado: %+v", got[0])
+	}
+	if got[1].LocalPortNum != 8 || got[1].ChassisMac != "D8:EC:5E:60:C7:82" {
+		t.Fatalf("vecino 1 inesperado: %+v", got[1])
+	}
+}
+
+func TestLldpMgmtAddrs(t *testing.T) {
+	got := lldpMgmtAddrs(lgs310cManAddrPdus())
+	if got["5.1"] != "192.168.1.80" {
+		t.Fatalf("mgmt 5.1 inesperada: %q", got["5.1"])
+	}
+	if len(got) != 1 {
+		t.Fatalf("solo IPv4 debe indexarse: %+v", got)
+	}
+}
+
+func TestLldpCapsFromBits(t *testing.T) {
+	cases := []struct {
+		b    []byte
+		want []string
+	}{
+		{[]byte{0x10, 0x00}, []string{"Wlan"}},                  // LGS310C real (lldpd PC)
+		{[]byte{0x28, 0x00}, []string{"Bridge", "Router"}},      // switch/router típico
+		{[]byte{0x01, 0x00}, []string{"Station"}},
+		{[]byte{0x39, 0x00}, []string{"Bridge", "Wlan", "Router", "Station"}},
+		{nil, nil},
+		{[]byte{0x00, 0x00}, nil},
+	}
+	for i, c := range cases {
+		if got := lldpCapsFromBits(c.b); !reflect.DeepEqual(got, c.want) {
+			t.Errorf("caso %d: got %v, want %v", i, got, c.want)
+		}
+	}
+}

+ 7 - 0
server-go/internal/snmp/oids.go

@@ -32,4 +32,11 @@ const (
 	// OidDot1qTpFdbPort: tabla FDB de Q-BRIDGE MIB (RFC 4363). Algunos
 	// switches gestionados solo la exponen (y no la dot1d) → fallback (#661).
 	OidDot1qTpFdbPort = ".1.3.6.1.2.1.17.7.1.2.2.1.2"
+
+	// LLDP-MIB (IEEE 802.1AB): tabla de vecinos remotos y sus direcciones de
+	// gestión (#931). Los switches SNMP que la exponen anuncian qué equipo
+	// cuelga de cada puerto; alimenta routerPolled.lldp con el mismo
+	// contrato que la sonda lldpd de los routers (#300).
+	OidLldpRemTable   = ".1.0.8802.1.1.2.1.4.1.1"
+	OidLldpRemManAddr = ".1.0.8802.1.1.2.1.4.2.1"
 )

+ 28 - 0
server-go/internal/snmp/snmp_test.go

@@ -216,3 +216,31 @@ func TestSortByIndex(t *testing.T) {
 		}
 	}
 }
+
+// #1115: la tarjeta de puertos solo lista bocas físicas. Verificado en un
+// LGS310C real: po1-8 (ieee8023adLag) y vlan1 (l3ipvlan) fuera; las 10
+// ethernetCsmacd dentro. El filtro es por exclusión: un switch que no
+// reporta ifType (Type=0) conserva sus puertos.
+func TestPhysicalIfPorts(t *testing.T) {
+	in := []PortStats{
+		{Index: 1, Name: "Slot0/1", Type: 6},
+		{Index: 10, Name: "Slot0/10", Type: 6},
+		{Index: 53, Name: "po1", Type: 161},
+		{Index: 61, Name: "vlan1", Type: 136},
+		{Index: 70, Name: "br0", Type: 209},
+		{Index: 71, Name: "lo", Type: 24},
+		{Index: 72, Name: "tun0", Type: 131},
+		{Index: 73, Name: "vlan2", Type: 135},
+		{Index: 74, Name: "mgmt", Type: 53},
+		{Index: 80, Name: "weird0", Type: 0}, // sin ifType reportado: se conserva
+	}
+	got := physicalIfPorts(in)
+	if len(got) != 3 {
+		t.Fatalf("esperaba 3 puertos físicos, obtuve %d: %+v", len(got), got)
+	}
+	for i, want := range []int{1, 10, 80} {
+		if got[i].Index != want {
+			t.Fatalf("puerto %d: Index %d, esperaba %d", i, got[i].Index, want)
+		}
+	}
+}