github.com/lastbackend/toolkit@v0.0.0-20241020043710-cafa37b95aad/pkg/util/addr/addr.go (about)

     1  /*
     2  Copyright [2014] - [2023] The Last.Backend authors.
     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      http://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 addr
    18  
    19  import (
    20  	"net"
    21  )
    22  
    23  func addrToIP(addr net.Addr) net.IP {
    24  	switch v := addr.(type) {
    25  	case *net.IPAddr:
    26  		return v.IP
    27  	case *net.IPNet:
    28  		return v.IP
    29  	default:
    30  		return nil
    31  	}
    32  }
    33  
    34  func localIPs() []string {
    35  	ifaces, err := net.Interfaces()
    36  	if err != nil {
    37  		return nil
    38  	}
    39  
    40  	var ipAddrs []string
    41  
    42  	for _, iface := range ifaces {
    43  		addrs, err := iface.Addrs()
    44  		if err != nil {
    45  			continue // ignore error
    46  		}
    47  
    48  		for _, addr := range addrs {
    49  			if ip := addrToIP(addr); ip != nil {
    50  				ipAddrs = append(ipAddrs, ip.String())
    51  			}
    52  		}
    53  	}
    54  
    55  	return ipAddrs
    56  }
    57  
    58  func DetectIP() (string, error) {
    59  	conn, err := net.Dial("udp", "127.0.0.1:9000")
    60  	if err != nil {
    61  		return "", err
    62  	}
    63  
    64  	defer conn.Close()
    65  	addr := conn.LocalAddr().(*net.UDPAddr)
    66  	return addr.IP.String(), nil
    67  }
    68  
    69  func IPs() []string {
    70  	return localIPs()
    71  }