github.com/openziti/transport@v0.1.5/dialer.go (about)

     1  /*
     2  	Copyright NetFoundry, Inc.
     3  
     4  	Licensed under the Apache License, Version 2.0 (the "License");
     5  	you may not use this file except in compliance with the License.
     6  	You may obtain a copy of the License at
     7  
     8  	https://www.apache.org/licenses/LICENSE-2.0
     9  
    10  	Unless required by applicable law or agreed to in writing, software
    11  	distributed under the License is distributed on an "AS IS" BASIS,
    12  	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  	See the License for the specific language governing permissions and
    14  	limitations under the License.
    15  */
    16  
    17  package transport
    18  
    19  import (
    20  	"fmt"
    21  	"github.com/pkg/errors"
    22  	"net"
    23  	"time"
    24  )
    25  
    26  // Creates a dialer and sets the local ip used for dialing
    27  //
    28  func NewDialerWithLocalBinding(addressType string, timeout time.Duration, localBinding string) (*net.Dialer, error) {
    29  
    30  	dialer := &net.Dialer{
    31  		Timeout: timeout,
    32  	}
    33  
    34  	if localBinding != "" {
    35  		iface, err := ResolveInterface(localBinding)
    36  
    37  		if err != nil {
    38  			return nil, err
    39  		}
    40  
    41  		addrs, err := iface.Addrs()
    42  
    43  		if err != nil {
    44  			return nil, err
    45  		}
    46  
    47  		if len(addrs) == 0 {
    48  			return nil, errors.New(fmt.Sprintf("no ip addresses assigned to interface %s", localBinding))
    49  		}
    50  
    51  		switch addressType {
    52  		case "udp":
    53  			dialer.LocalAddr = &net.UDPAddr{
    54  				IP: addrs[0].(*net.IPNet).IP,
    55  			}
    56  		case "tcp", "tls":
    57  			dialer.LocalAddr = &net.TCPAddr{
    58  				IP: addrs[0].(*net.IPNet).IP,
    59  			}
    60  		default:
    61  			return nil, errors.New(fmt.Sprintf("Unsupported addressType: %s", addressType))
    62  		}
    63  	}
    64  
    65  	return dialer, nil
    66  }