@@ -24,13 +24,13 @@ func init() {
2424 flag .StringVar (& ip , "ip" , "192.168.1.11/24" , "IP network from where the command will be executed" )
2525 flag .StringVar (& intf , "interface" , "eth0" , "interface used to get out of the network" )
2626 flag .StringVar (& command , "command" , "ip route" , "command to be executed" )
27- flag .StringVar (& gateway , "gw" , "" , "gateway of the request" )
27+ flag .StringVar (& gateway , "gw" , "" , "gateway of the request (default will be the default route of the given interface) " )
2828 flag .StringVar (& logLevel , "log-level" , "info" , "min level of logs to print" )
2929 flag .StringVar (
3030 & nsPath ,
3131 "ns-path" ,
32- fmt . Sprintf ( "/var/run/netns/w000t%d" , os . Getpid ()) ,
33- "path of the temporary namespace to be created, default will be /var/run/netns/w000t$PID" ,
32+ "" ,
33+ "path of the temporary namespace to be created ( default will be /var/run/netns/w000t$PID) " ,
3434 )
3535 flag .Parse ()
3636}
@@ -75,6 +75,33 @@ func main() {
7575 }
7676 log .Debugf ("%s : %+v" , intf , eth .Attrs ().Flags )
7777
78+ // If no nsPath is given, we'll use one named like
79+ // /var/run/netns/w000t$PID
80+ if nsPath == "" {
81+ nsPath = fmt .Sprintf ("/var/run/netns/w000t%d" , os .Getpid ())
82+ }
83+
84+ // If no gateway is specified, we'll use the first route of the given interface
85+ if gateway == "" {
86+ routes , err := netlink .RouteList (eth , netlink .FAMILY_V4 )
87+ if err != nil {
88+ log .Warn ("Failed to get the route of the interface: " , err )
89+ return
90+ }
91+
92+ for _ , r := range routes {
93+ if r .Gw != nil {
94+ gateway = r .Gw .String ()
95+ break
96+ }
97+ }
98+ if gateway == "" {
99+ log .Warnf ("Couldn't find a default gateway for the specified interface" )
100+ return
101+ }
102+ }
103+ gwaddr := net .ParseIP (gateway )
104+
78105 // ============================== Create the macVLAN
79106
80107 log .Debug ("Create a new macVlan" )
@@ -156,7 +183,6 @@ func main() {
156183 log .Warn ("Failed to add the IP to the macVlan: " , err )
157184 return
158185 }
159- gwaddr := net .ParseIP (gateway )
160186
161187 log .Debug ("Set the macVlan interface UP" )
162188 // ============================= Set the link up in the namespace
0 commit comments