...

Source file src/discovery/utils/net.go

Documentation: discovery/utils

     1  /*
     2   * P2PFaaS - A framework for FaaS Load Balancing
     3   * Copyright (c) 2019. Gabriele Proietti Mattia <pm.gabriele@outlook.com>
     4   *
     5   * This program is free software: you can redistribute it and/or modify
     6   * it under the terms of the GNU General Public License as published by
     7   * the Free Software Foundation, either version 3 of the License, or
     8   * (at your option) any later version.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <https://www.gnu.org/licenses/>.
    17   */
    18  
    19  package utils
    20  
    21  import (
    22  	"discovery/log"
    23  	"net"
    24  	"strings"
    25  )
    26  
    27  type IPError struct{}
    28  
    29  func (e IPError) Error() string {
    30  	return "Could not get ip address"
    31  }
    32  
    33  func GetInternalIP(ifaceName string) (string, error) {
    34  	iface, err := net.InterfaceByName(ifaceName)
    35  	if err != nil {
    36  		log.Log.Errorf("Could not find interface \"%s\"", ifaceName)
    37  		return "", IPError{}
    38  	}
    39  	if iface.Flags&net.FlagUp == 0 {
    40  		log.Log.Errorf("Interface \"%s\" is down", ifaceName)
    41  		return "", IPError{} // interface down
    42  	}
    43  	if iface.Flags&net.FlagLoopback != 0 {
    44  		log.Log.Errorf("Interface \"%s\" is loopback", ifaceName)
    45  		return "", IPError{} // loopback interface
    46  	}
    47  
    48  	addresses, err := iface.Addrs()
    49  
    50  	for _, addr := range addresses {
    51  		var ip net.IP
    52  		switch v := addr.(type) {
    53  		case *net.IPNet:
    54  			ip = v.IP
    55  		case *net.IPAddr:
    56  			ip = v.IP
    57  		}
    58  		if ip == nil || ip.IsLoopback() {
    59  			continue
    60  		}
    61  		ip = ip.To4()
    62  		if ip == nil {
    63  			continue // not an ipv4 address
    64  		}
    65  		return ip.String(), nil
    66  	}
    67  
    68  	log.Log.Errorf("Could not get ip for \"%s\"", ifaceName)
    69  	return "", IPError{}
    70  }
    71  
    72  /*
    73   * Generic utils
    74   */
    75  
    76  func IsolateIPFromPort(ip string) string {
    77  	lastColon := strings.LastIndex(ip, ":")
    78  	if lastColon == -1 {
    79  		return ip
    80  	}
    81  	trueIp := ip[0:lastColon]
    82  	return trueIp
    83  }
    84  

View as plain text