Quero testar uma aplicação que executa uma pilha IPv6 completa no espaço do usuário. A aplicação deve processar e enviar quadros Ethernet. Para isso, quero configurar uma interface de rede no Linux que eu possa acessar do meu computador local como se fosse outro participante da rede. Li que deveria usar um dispositivo de tap para isso. Então, criei um script para configurar uma interface e uma aplicação de teste.
Aqui está meu script para configurar a interface:
#!/bin/bash
MAC_ADDR="00:11:22:33:44:55"
IP_ADDR="2001:db8::2"
setup() {
# Create the TAP interface (if not already created)
ip tuntap add dev tap0 mode tap
# Assign an IPv6 address to the TAP interface
ip -6 addr add "${IP_ADDR}/64" dev tap0
# Bring the TAP interface up
ip link set dev tap0 up
# Set a custom MAC address for the TAP interface
# (Replace with your desired MAC address)
ip link set dev tap0 address $MAC_ADDR
# Disable kernel IPv6 handling on this interface
sysctl -w net.ipv6.conf.tap0.forwarding=0
sysctl -w net.ipv6.conf.tap0.accept_ra=0
# Print interface details to verify the MAC address and IP
ip addr show dev tap0
}
cleanup() {
ip link set tap0 down || true
ip tuntap del dev tap0 mode tap
}
# Setup tap interface
setup
# Cleanup when exiting
trap cleanup SIGINT
# Keep the interface up indefinitely
echo "Press Ctrl+C to bring down the interface"
sleep infinity
Esta é minha aplicação de teste:
// TunInterface.h
#pragma once
#include <string>
#include <functional>
#include <sys/socket.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <iostream>
#include <netinet/if_ether.h>
#include <netinet/ip.h>
class TunInterface {
public:
TunInterface(const std::string& dev_name,
std::function<void(const unsigned char*, size_t)> recv_callback,
const unsigned char* mac_address = nullptr)
: dev_name(dev_name), receive_callback(recv_callback), mac_filter(mac_address) {
// Open the TUN device
tun_fd = open("/dev/net/tun", O_RDWR);
if (tun_fd < 0) {
std::cerr << "Failed to open TUN device" << std::endl;
exit(1);
}
struct ifreq ifr;
std::memset(&ifr, 0, sizeof(ifr));
std::strncpy(ifr.ifr_name, dev_name.c_str(), IFNAMSIZ);
// Set up the TUN interface
if (ioctl(tun_fd, TUNSETIFF, &ifr) < 0) {
std::cerr << "Failed to configure TUN interface" << std::endl;
close(tun_fd);
exit(1);
}
std::cout << "TUN interface " << dev_name << " configured successfully." << std::endl;
}
~TunInterface() {
close(tun_fd);
}
// Function to start receiving and calling the callback on incoming packets
void receive() {
unsigned char buffer[2048]; // Adjust the buffer size as needed
while (true) {
ssize_t len = read(tun_fd, buffer, sizeof(buffer));
if (len < 0) {
std::cerr << "Error reading from TUN interface" << std::endl;
continue;
}
// Call the user-defined callback
if (mac_filter && !is_mac_filtered(buffer)) {
// If the MAC address does not match the filter, skip the packet
continue;
}
receive_callback(buffer, len);
}
}
// Function to send a packet
void send(const unsigned char* data, size_t len) {
ssize_t bytes_written = write(tun_fd, data, len);
if (bytes_written < 0) {
std::cerr << "Error writing to TUN interface" << std::endl;
}
}
private:
int tun_fd;
std::string dev_name;
std::function<void(const unsigned char*, size_t)> receive_callback;
const unsigned char* mac_filter; // If nullptr, no filtering is done
bool is_mac_filtered(const unsigned char* packet) {
if (mac_filter) {
struct ethhdr* eth_header = reinterpret_cast<struct ethhdr*>(const_cast<unsigned char*>(packet));
return std::memcmp(eth_header->h_dest, mac_filter, ETH_ALEN) == 0;
}
return true; // No filter if mac_filter is nullptr
}
};
#endif
#include "TapInterface.h"
#include <iostream>
int main() {
// Define the MAC address for filtering (e.g., 00:11:22:33:44:55)
uint8_t macAddr[6] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55 };
// Create a TapInterface with MAC filtering enabled
TapInterface tap("tap0", macAddr);
if (!tap.isValid()) {
std::cerr << "Failed to create TAP interface\n";
return 1;
}
// Register a callback to handle received frames
tap.registerReceiveCallback([](const uint8_t* data, size_t len) {
std::cout << "Received frame of length " << len << " bytes\n";
});
std::cout << "Listening on tap0. Press Ctrl-C to exit.\n";
while (true) pause(); // Or use any other suitable loop
}
Quando executo, ping6 2001:db8::2
espero ver pelo menos quadros Ethernet de descoberta de vizinhos no meu aplicativo de teste. Mas não vejo nada. Em vez disso, recebo respostas às minhas tentativas de ping6 assim que inicio o aplicativo de teste. Parece que o kernel ainda está interferindo. Tentei uma abordagem semelhante usando um dispositivo tun e funcionou, mas não funcionou na Camada 2. Estou usando o Ubuntu 24.04.
O que pode estar errado? Obrigado.
2001:db8::2
é o seu próprio endereço local. Pacotes enviados para o endereço local da máquina (ou seja, um endereço atribuído diretamente a uma interface) nunca são enviados através da interface, pois a interface não fará um "loop" desses pacotes para você – o que significa que o host nunca veria sua própria consulta de Descoberta de Vizinhos se enviasse uma; e nunca "receberia" nenhum quadro que teria enviado para seu próprio endereço MAC. Em vez disso, todos esses pacotes são implicitamente roteados através delalo
(mesmo que a tabela de roteamento "local" não mostre isso).Faça ping em algum outro endereço do /64 e você deverá ver os pacotes.
Seu aplicativo não é a mesma entidade de rede que o sistema operacional host Linux – ele existe como uma entidade de rede separada, na "outra extremidade do cabo", por assim dizer – então ele deve ter um endereço IP separado do host, bem como um endereço MAC separado.