Configuring a virtual network namespace in Fedora (or any Linux distribution) can be done using the ip command, which is part of the iproute2 package (usually installed by default). Below is a basic script that sets up a virtual network namespace, creates a virtual Ethernet pair, configures the interface, and allows the namespace to connect to the internet.
Script to Configure Virtual Network Namespace
#!/bin/bash
# Define the namespace and interface names
NAMESPACE="mynamespace"
VETH0="veth0"
VETH1="veth1"
BRIDGE="br0"
IP_ADDR="192.168.100.1/24" # IP address for the host side
NS_IP_ADDR="192.168.100.2/24" # IP address for the namespace
# Create a new network namespace
ip netns add $NAMESPACE
# Create a virtual ethernet pair
ip link add $VETH0 type veth peer name $VETH1
# Move the second virtual ethernet interface to the namespace
ip link set $VETH1 netns $NAMESPACE
# Assign IP addresses to the interfaces
ip addr add $IP_ADDR dev $VETH0
ip netns exec $NAMESPACE ip addr add $NS_IP_ADDR dev $VETH1
# Bring up the interfaces
ip link set $VETH0 up
ip netns exec $NAMESPACE ip link set $VETH1 up
# Optionally, set up a bridge if needed
# If you're connecting to a bridge, uncomment the following lines
# and create the bridge
# ip link add name $BRIDGE type bridge
# ip link set $BRIDGE up
# ip link set $VETH0 master $BRIDGE
# ip netns exec $NAMESPACE ip link set $VETH1 master $BRIDGE
# Enable forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# Configure NAT for internet access (assuming you have one interface connected to the internet)
# Replace <YOUR_INTERNET_INTERFACE> with your real internet interface name (e.g., eth0, ens33)
iptables -t nat -A POSTROUTING -s $NS_IP_ADDR -o <YOUR_INTERNET_INTERFACE> -j MASQUERADE
iptables -A FORWARD -i <YOUR_INTERNET_INTERFACE> -o $VETH0 -j ACCEPT
iptables -A FORWARD -i $VETH0 -o <YOUR_INTERNET_INTERFACE> -j ACCEPT
# Notify completion
echo "Virtual Network Namespace '$NAMESPACE' created with internet access."
Instructions to Use the Script:
- Save the script above to a file, for example,
setup_namespace.sh.
- Make the script executable:
chmod +x setup_namespace.sh
- Run the script with root privileges:
sudo ./setup_namespace.sh
Important Notes:
- Replace
<YOUR_INTERNET_INTERFACE> with the actual network interface name that is connected to the internet (you can find this using the ip a command).
- Ensure that
iptables is installed and running; otherwise, adjust the firewall rules as needed.
- The script sets up a basic NAT configuration for accessing the internet from the namespace. Adjust the IPs and network configuration as required for your specific use case.
- The namespace can be accessed afterward by using commands like
ip netns exec mynamespace <command>.