github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/commons/ipx/ip.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     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  
    18  package ipx
    19  
    20  import (
    21  	"github.com/aacfactory/fns/commons/bytex"
    22  	"net"
    23  	"os"
    24  )
    25  
    26  func GetGlobalUniCastIpFromHostname() (v net.IP) {
    27  	hostname, _ := os.Hostname()
    28  	if hostname == "" {
    29  		hostname, _ = os.LookupEnv("HOSTNAME")
    30  	}
    31  	if hostname == "" {
    32  		return
    33  	}
    34  	ips, err := net.LookupIP(hostname)
    35  	if err != nil {
    36  		return
    37  	}
    38  	for _, ip := range ips {
    39  		if ip.IsGlobalUnicast() {
    40  			v = ip
    41  			break
    42  		}
    43  	}
    44  	return
    45  }
    46  
    47  func CanonicalizeIp(ip []byte) []byte {
    48  	isIPv6 := false
    49  	for i := 0; !isIPv6 && i < len(ip); i++ {
    50  		switch ip[i] {
    51  		case '.':
    52  			// IPv4
    53  			return ip
    54  		case ':':
    55  			// IPv6
    56  			isIPv6 = true
    57  			break
    58  		}
    59  	}
    60  	if !isIPv6 {
    61  		return ip
    62  	}
    63  	ipv6 := net.ParseIP(bytex.ToString(ip))
    64  	if ipv6 == nil {
    65  		return ip
    66  	}
    67  	return bytex.FromString(ipv6.Mask(net.CIDRMask(64, 128)).String())
    68  }