github.com/alibaba/ilogtail/pkg@v0.0.0-20250526110833-c53b480d046c/util/net_helper.go (about)

     1  // Copyright 2021 iLogtail Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package util
    16  
    17  import (
    18  	"errors"
    19  	"log"
    20  	"net"
    21  	"os"
    22  )
    23  
    24  var ipAddress string
    25  var hostName string
    26  
    27  func init() {
    28  	var err error
    29  	ipAddress, err = getExternalIP()
    30  	if err != nil {
    31  		log.Println(err)
    32  	}
    33  	hostName, _ = os.Hostname()
    34  }
    35  
    36  // SetNetworkIdentification updates return values of GetIPAddress and GetHostName.
    37  // NOTE: It is not thread-safety, this is called by plugin_manager.LoadGlobalConfig only.
    38  func SetNetworkIdentification(hostIP, hostname string) {
    39  	ipAddress = hostIP
    40  	hostName = hostname
    41  }
    42  
    43  func GetIPAddress() string {
    44  	return ipAddress
    45  }
    46  
    47  func GetHostName() string {
    48  	return hostName
    49  }
    50  
    51  func getExternalIP() (string, error) {
    52  	ifaces, err := net.Interfaces()
    53  	if err != nil {
    54  		return "", err
    55  	}
    56  	for _, iface := range ifaces {
    57  		if iface.Flags&net.FlagUp == 0 {
    58  			continue // interface down
    59  		}
    60  		if iface.Flags&net.FlagLoopback != 0 {
    61  			continue // loopback interface
    62  		}
    63  		addrs, err := iface.Addrs()
    64  		if err != nil {
    65  			return "", err
    66  		}
    67  		for _, addr := range addrs {
    68  			var ip net.IP
    69  			switch v := addr.(type) {
    70  			case *net.IPNet:
    71  				ip = v.IP
    72  			case *net.IPAddr:
    73  				ip = v.IP
    74  			}
    75  			if ip == nil || ip.IsLoopback() {
    76  				continue
    77  			}
    78  			ip = ip.To4()
    79  			if ip == nil {
    80  				continue // not an ipv4 address
    81  			}
    82  			return ip.String(), nil
    83  		}
    84  	}
    85  	return "", errors.New("are you connected to the network?")
    86  }
    87  
    88  func TryConvertLocalhost2RealIP(ip string) string {
    89  	if ip == "localhost" || ip == "127.0.0.1" || ip == "0.0.0.0" {
    90  		return GetIPAddress()
    91  	}
    92  	return ip
    93  }