Revision af1ccf93 mininet/nodelib.py

View differences:

mininet/nodelib.py
5 5
"""
6 6

  
7 7
from mininet.node import Node, Switch
8
from mininet.log import info
8
from mininet.log import info, warn
9 9
from mininet.moduledeps import pathCheck
10 10

  
11
import re
11 12

  
12 13
class LinuxBridge( Switch ):
13 14
    "Linux Bridge (with optional spanning tree)"
......
63 64
class NAT( Node ):
64 65
    """NAT: Provides connectivity to external network"""
65 66

  
66
    def __init__( self, name, inetIntf='eth0', subnet='10.0/8', localIntf=None, **params):
67
    def __init__( self, name, inetIntf=None, subnet='10.0/8', localIntf=None, **params):
67 68
        super( NAT, self ).__init__( name, **params )
68 69

  
69 70
        """Start NAT/forwarding between Mininet and external network
70 71
        inetIntf: interface for internet access
71 72
        subnet: Mininet subnet (default 10.0/8)="""
72
        self.inetIntf = inetIntf
73
        self.inetIntf = inetIntf if inetIntf else self.getGatewayIntf()
73 74
        self.subnet = subnet
74 75
        self.localIntf = localIntf
75 76

  
......
96 97
        self.cmd( 'iptables -I FORWARD -i', self.localIntf, '-d', self.subnet, '-j DROP' )
97 98
        self.cmd( 'iptables -A FORWARD -i', self.localIntf, '-s', self.subnet, '-j ACCEPT' )
98 99
        self.cmd( 'iptables -A FORWARD -i', self.inetIntf, '-d', self.subnet, '-j ACCEPT' )
99
        self.cmd( 'iptables -t nat -A POSTROUTING -o ', self.inetIntf, '-j MASQUERADE' )
100
        self.cmd( 'iptables -t nat -A POSTROUTING -o ', self.inetIntf, '-s', self.subnet, '-j MASQUERADE' )
100 101

  
101 102
        # Instruct the kernel to perform forwarding
102 103
        self.cmd( 'sysctl net.ipv4.ip_forward=1' )
......
108 109
        line = '\niface %s inet manual\n' % intf
109 110
        config = open( cfile ).read()
110 111
        if ( line ) not in config:
111
            info( '*** Adding "' + line.strip() + '" to ' + cfile )
112
            info( '*** Adding "' + line.strip() + '" to ' + cfile + '\n' )
112 113
            with open( cfile, 'a' ) as f:
113 114
                f.write( line )
114 115
        # Probably need to restart network-manager to be safe -
115 116
        # hopefully this won't disconnect you
116 117
        self.cmd( 'service network-manager restart' )
117 118

  
119
    def getGatewayIntf( self ):
120
        routes = self.cmd( 'ip route show' )
121
        match = re.search('default via \S+ dev (\S+)', routes )
122
        if match:
123
            return match.group( 1 )
124
        else:
125
            warn( 'There is no default route set. Using eth0 as gateway interface...\n' )
126
            return 'eth0'
127

  
118 128
    def terminate( self ):
119 129
        """Stop NAT/forwarding between Mininet and external network"""
120 130
        # Flush any currently active rules

Also available in: Unified diff