@@ -42,6 +42,11 @@ func configureDevice(wgcl *wgctrl.Client, options *Options, peerPubKey wgtypes.K
4242 switch options .GwOptions .Mode {
4343 case gateway .ModeServer :
4444 confdev .ListenPort = & options .ListenPort
45+
46+ endpoint := getExistingEndpoint (wgcl , peerPubKey )
47+ if endpoint != nil {
48+ confdev .Peers [0 ].Endpoint = endpoint
49+ }
4550 case gateway .ModeClient :
4651 confdev .Peers [0 ].Endpoint = & net.UDPAddr {
4752 IP : options .EndpointIP ,
@@ -56,3 +61,48 @@ func configureDevice(wgcl *wgctrl.Client, options *Options, peerPubKey wgtypes.K
5661 }
5762 return nil
5863}
64+
65+ func getExistingEndpoint (wgcl * wgctrl.Client , peerPubKey wgtypes.Key ) * net.UDPAddr {
66+ peer := getExistingPeer (wgcl , peerPubKey )
67+
68+ if peer == nil {
69+ return nil
70+ }
71+
72+ if peer .Endpoint != nil {
73+ klog .Infof ("Discovered endpoint %s for peer %s" , peer .Endpoint , peerPubKey .String ())
74+ return peer .Endpoint
75+ }
76+
77+ return nil
78+ }
79+
80+ func getExistingPeer (wgcl * wgctrl.Client , peerPubKey wgtypes.Key ) * wgtypes.Peer {
81+ dev := getExistingDevice (wgcl )
82+
83+ if dev == nil {
84+ return nil
85+ }
86+
87+ for i := range dev .Peers {
88+ if dev .Peers [i ].PublicKey == peerPubKey {
89+ klog .Infof ("Found existing peer for key %s" , peerPubKey .String ())
90+ return & dev .Peers [i ]
91+ }
92+ }
93+
94+ klog .Infof ("No existing peer %s found" , peerPubKey .String ())
95+ return nil
96+ }
97+
98+ func getExistingDevice (wgcl * wgctrl.Client ) * wgtypes.Device {
99+ dev , err := wgcl .Device (tunnel .TunnelInterfaceName )
100+
101+ if err == nil {
102+ klog .Infof ("Found existing device %s" , tunnel .TunnelInterfaceName )
103+ return dev
104+ }
105+
106+ klog .Infof ("No existing device %s found" , tunnel .TunnelInterfaceName )
107+ return nil
108+ }
0 commit comments