How to Programmatically Detect NICs Connected to the Same Switch in Linux Using LLDP and ARP Techniques


15 views

When managing Linux servers in enterprise environments, we often encounter scenarios where multiple network interfaces are physically connected to different switches without proper documentation. This becomes particularly problematic when configuring NIC bonding or troubleshooting network segmentation issues.

Here are the most reliable methods to identify interfaces on the same switch:

# Method 1: Using LLDP (Layer 2 Discovery Protocol)
sudo apt install lldpd
sudo systemctl start lldpd
lldpcli show neighbors

# Method 2: ARP-based detection
arp-scan --interface=eth0 --localnet
arp-scan --interface=eth1 --localnet

For scripting purposes, we can create a Python solution that:

#!/usr/bin/env python3
import subprocess
import re

def get_switch_ports():
    result = {}
    try:
        output = subprocess.check_output(["lldpcli", "show", "neighbors"], 
                                     universal_newlines=True)
        for line in output.split('\n'):
            if 'Interface:' in line:
                current_iface = line.split()[-1].strip(',')
            if 'SysName:' in line:
                switch_name = line.split()[-1]
                result[current_iface] = switch_name
    except FileNotFoundError:
        print("LLDP not installed, falling back to ARP method")
        result = get_arp_based_matching()
    return result

def get_arp_based_matching():
    # Implementation would scan ARP tables and compare
    pass

if __name__ == "__main__":
    switch_map = get_switch_ports()
    print("Interface to Switch Mapping:")
    for iface, switch in switch_map.items():
        print(f"{iface} -> {switch}")

When LLDP isn't available, consider these methods:

# Using ethtool to check peer information
sudo ethtool --show-ring eth0 | grep -i peer

# Checking switch port statistics
cat /sys/class/net/eth0/statistics/tx_packets
cat /sys/class/net/eth1/statistics/tx_packets

When preparing interfaces for bonding, verify:

  • Identical speed and duplex settings
  • Consistent VLAN configurations
  • Same upstream switch for active-active bonds
# Sample bonding configuration check
cat /proc/net/bonding/bond0 | grep -i 'slave\|status'

For reliable automation:

  1. Implement consistent network documentation
  2. Use configuration management tools to track connections
  3. Schedule regular topology validation checks

When configuring network bonding on Linux systems with multiple interfaces, a critical first step is identifying which NICs share the same physical switch. This becomes particularly challenging when:

  • Multiple interfaces are connected without IP addresses
  • Network documentation is incomplete
  • Switch access isn't available
  • Physical labeling is inconsistent

Method 1: LLDP Protocol (Recommended)

The Link Layer Discovery Protocol (LLDP) is the most reliable way to detect switch connections:


# Install lldpad if not present
sudo apt install lldpad

# Enable lldpad service
sudo systemctl start lldpad
sudo lldptool -L -i eth0 adminStatus=rxtx
sudo lldptool -T -i eth0 -V sysName

# Repeat for other interfaces and compare switch names

Method 2: MAC Address Table Analysis

When LLDP isn't available, we can analyze MAC address tables:


#!/bin/bash
# Get MAC addresses visible on each interface
for iface in eth{0..5}; do
    echo "Checking $iface:"
    sudo ip -br link show dev $iface | awk '{print $3}'
    sudo tcpdump -i $iface -c 5 -e -n 2>&1 | grep -oE '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'
    echo "------------------"
done

Method 3: Custom ICMP Broadcast Detection

For environments where broadcast traffic is permitted:


# Python script to detect shared broadcast domains
import socket
import fcntl
import struct
import time

def get_mac(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', ifname[:15]))
    return ':'.join(['%02x' % ord(char) for char in info[18:24]])

def monitor_broadcasts(interface):
    # Implement broadcast monitoring logic here
    pass

# Main detection logic would go here

Once interfaces are identified as sharing the same switch, we can automate bonding setup:


#!/bin/bash
# Sample bonding configuration script
INTERFACE_PAIRS=$(discover_shared_switch_interfaces) # Implement this function

for pair in $INTERFACE_PAIRS; do
    IFS=',' read -r if1 if2 <<< "$pair"
    echo "Configuring bond for $if1 and $if2"
    
    sudo nmcli con add type bond ifname bond0 mode active-backup
    sudo nmcli con add type bond-slave ifname $if1 master bond0
    sudo nmcli con add type bond-slave ifname $if2 master bond0
    
    # Additional configuration as needed
done

After configuration, verify bonding status:


cat /proc/net/bonding/bond0
ethtool bond0
ip link show bond0

Common issues to check:

  • Interface speed/duplex mismatches
  • Switch port configuration (LACP settings if using mode 4)
  • MAC address flapping