github.com/containerd/nerdctl@v1.7.7/pkg/testutil/nettestutil/nettestutil.go (about) 1 /* 2 Copyright The containerd 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 nettestutil 18 19 import ( 20 "crypto/rand" 21 "crypto/tls" 22 "fmt" 23 "net" 24 "net/http" 25 "time" 26 27 "github.com/containerd/errdefs" 28 ) 29 30 func HTTPGet(urlStr string, attempts int, insecure bool) (*http.Response, error) { 31 var ( 32 resp *http.Response 33 err error 34 ) 35 if attempts < 1 { 36 return nil, errdefs.ErrInvalidArgument 37 } 38 client := &http.Client{ 39 Timeout: 3 * time.Second, 40 Transport: &http.Transport{ 41 TLSClientConfig: &tls.Config{ 42 InsecureSkipVerify: insecure, 43 }, 44 }, 45 } 46 for i := 0; i < attempts; i++ { 47 resp, err = client.Get(urlStr) 48 if err == nil { 49 return resp, nil 50 } 51 time.Sleep(100 * time.Millisecond) 52 } 53 return nil, fmt.Errorf("error after %d attempts: %w", attempts, err) 54 } 55 56 func NonLoopbackIPv4() (net.IP, error) { 57 addrs, err := net.InterfaceAddrs() 58 if err != nil { 59 return nil, err 60 } 61 for _, addr := range addrs { 62 ip, _, err := net.ParseCIDR(addr.String()) 63 if err != nil { 64 continue 65 } 66 ipv4 := ip.To4() 67 if ipv4 == nil { 68 continue 69 } 70 if ipv4.IsLoopback() { 71 continue 72 } 73 return ipv4, nil 74 } 75 return nil, fmt.Errorf("non-loopback IPv4 address not found, attempted=%+v: %w", addrs, errdefs.ErrNotFound) 76 } 77 78 func GenerateMACAddress() (string, error) { 79 buf := make([]byte, 6) 80 if _, err := rand.Read(buf); err != nil { 81 return "", err 82 } 83 // make sure byte 0 (broadcast) of the first byte is not set 84 // and byte 1 (local) is set 85 buf[0] = buf[0]&254 | 2 86 return fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]), nil 87 }