github.com/cloudwego/hertz@v0.9.3/pkg/common/utils/network.go (about) 1 /* 2 * Copyright 2022 CloudWeGo 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 utils 18 19 import "net" 20 21 const ( 22 UNKNOWN_IP_ADDR = "-" 23 ) 24 25 var localIP string 26 27 // LocalIP returns host's ip 28 func LocalIP() string { 29 return localIP 30 } 31 32 // getLocalIp enumerates local net interfaces to find local ip, it should only be called in init phase 33 func getLocalIp() string { 34 inters, err := net.Interfaces() 35 if err != nil { 36 return UNKNOWN_IP_ADDR 37 } 38 for _, inter := range inters { 39 if inter.Flags&net.FlagLoopback != net.FlagLoopback && 40 inter.Flags&net.FlagUp != 0 { 41 addrs, err := inter.Addrs() 42 if err != nil { 43 return UNKNOWN_IP_ADDR 44 } 45 for _, addr := range addrs { 46 if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { 47 return ipnet.IP.String() 48 } 49 } 50 } 51 } 52 53 return UNKNOWN_IP_ADDR 54 } 55 56 func init() { 57 localIP = getLocalIp() 58 } 59 60 // TLSRecordHeaderLooksLikeHTTP reports whether a TLS record header 61 // looks like it might've been a misdirected plaintext HTTP request. 62 func TLSRecordHeaderLooksLikeHTTP(hdr [5]byte) bool { 63 switch string(hdr[:]) { 64 case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO": 65 return true 66 } 67 return false 68 }