Best K6 code snippet using lib.splitHostPort
hosts.go
Source:hosts.go
1// Copyright 2018 ETH Zurich2//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 at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// 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 and13// limitations under the License.14package appnet15import (16 "fmt"17 "net"18 "regexp"19 "strconv"20 "github.com/scionproto/scion/go/lib/addr"21 "github.com/scionproto/scion/go/lib/snet"22)23var (24 resolveEtcHosts Resolver = &hostsfileResolver{"/etc/hosts"}25 resolveEtcScionHosts Resolver = &hostsfileResolver{"/etc/scion/hosts"}26 resolveRains Resolver = nil27)28var (29 addrRegexp = regexp.MustCompile(`^(\d+-[\d:A-Fa-f]+),\[([^\]]+)\]$`)30 hostPortRegexp = regexp.MustCompile(`^((?:[-.\da-zA-Z]+)|(?:\d+-[\d:A-Fa-f]+,(\[[^\]]+\]|[^\]:]+))):(\d+)$`)31)32const (33 addrRegexpIaIndex = 134 addrRegexpL3Index = 235 hostPortRegexpHostIndex = 136 hostPortRegexpPortIndex = 237)38// SplitHostPort splits a host:port string into host and port variables.39// This is analogous to net.SplitHostPort, which however refuses to handle SCION addresses.40// The address can be of the form of a SCION address (i.e. of the form "ISD-AS,[IP]:port")41// or in the form of "hostname:port".42func SplitHostPort(hostport string) (host, port string, err error) {43 match := hostPortRegexp.FindStringSubmatch(hostport)44 if match != nil {45 return match[hostPortRegexpHostIndex], match[hostPortRegexpPortIndex], nil46 }47 return "", "", fmt.Errorf("appnet.SplitHostPort: invalid address")48}49// ResolveUDPAddr parses the address and resolves the hostname.50// The address can be of the form of a SCION address (i.e. of the form "ISD-AS,[IP]:port")51// or in the form of "hostname:port".52// If the address is in the form of a hostname, the DefaultResolver is used to53// resolve the name.54func ResolveUDPAddr(address string) (*snet.UDPAddr, error) {55 return ResolveUDPAddrAt(address, DefaultResolver())56}57// ResolveUDPAddrAt parses the address and resolves the hostname.58// The address can be of the form of a SCION address (i.e. of the form "ISD-AS,[IP]:port")59// or in the form of "hostname:port".60// If the address is in the form of a hostname, resolver is used to resolve the name.61func ResolveUDPAddrAt(address string, resolver Resolver) (*snet.UDPAddr, error) {62 raddr, err := snet.ParseUDPAddr(address)63 if err == nil {64 return raddr, nil65 }66 hostStr, portStr, err := net.SplitHostPort(address)67 if err != nil {68 return nil, err69 }70 port, err := strconv.Atoi(portStr)71 if err != nil {72 return nil, err73 }74 host, err := resolver.Resolve(hostStr)75 if err != nil {76 return nil, err77 }78 ia := host.IA79 return &snet.UDPAddr{IA: ia, Host: &net.UDPAddr{IP: host.Host.IP(), Port: port}}, nil80}81// DefaultResolver returns the default name resolver, used in ResolveUDPAddr.82// It will use the following sources, in the given order of precedence, to83// resolve a name:84//85// - /etc/hosts86// - /etc/scion/hosts87// - RAINS, if a server is configured in /etc/scion/rains.cfg.88// Disabled if built with !norains.89func DefaultResolver() Resolver {90 return ResolverList{91 resolveEtcHosts,92 resolveEtcScionHosts,93 resolveRains,94 }95}96// MangleSCIONAddr mangles a SCION address string (if it is one) so it can be97// safely used in the host part of a URL.98func MangleSCIONAddr(address string) string {99 raddr, err := snet.ParseUDPAddr(address)100 if err != nil {101 return address102 }103 // Turn this into [IA,IP]:port format. This is a valid host in a URI, as per104 // the "IP-literal" case in RFC 3986, §3.2.2.105 // Unfortunately, this is not currently compatible with snet.ParseUDPAddr,106 // so this will have to be _unmangled_ before use.107 mangledAddr := fmt.Sprintf("[%s,%s]", raddr.IA, raddr.Host.IP)108 if raddr.Host.Port != 0 {109 mangledAddr += fmt.Sprintf(":%d", raddr.Host.Port)110 }111 return mangledAddr112}113// UnmangleSCIONAddr returns a SCION address that can be parsed with114// with snet.ParseUDPAddr.115// If the input is not a SCION address (e.g. a hostname), the address is116// returned unchanged.117// This parses the address, so that it can safely join host and port, with the118// brackets in the right place. Yes, this means this will be parsed twice.119//120// Assumes that address always has a port (this is enforced by the http3121// roundtripper code)122func UnmangleSCIONAddr(address string) string {123 host, port, err := net.SplitHostPort(address)124 if err != nil || port == "" {125 panic(fmt.Sprintf("UnmangleSCIONAddr assumes that address is of the form host:port %s", err))126 }127 // brackets are removed from [I-A,IP] part by SplitHostPort, so this can be128 // parsed with ParseUDPAddr:129 udpAddr, err := snet.ParseUDPAddr(host)130 if err != nil {131 return address132 }133 p, err := strconv.ParseUint(port, 10, 16)134 if err != nil {135 return address136 }137 udpAddr.Host.Port = int(p)138 return udpAddr.String()139}140// addrFromString parses a string to a snet.SCIONAddress141// XXX(matzf) this would optimally be part of snet142func addrFromString(address string) (snet.SCIONAddress, error) {143 parts := addrRegexp.FindStringSubmatch(address)144 if parts == nil {145 return snet.SCIONAddress{}, fmt.Errorf("no valid SCION address: %q", address)146 }147 ia, err := addr.IAFromString(parts[addrRegexpIaIndex])148 if err != nil {149 return snet.SCIONAddress{},150 fmt.Errorf("invalid IA string: %v", parts[addrRegexpIaIndex])151 }152 var l3 addr.HostAddr153 if hostSVC := addr.HostSVCFromString(parts[addrRegexpL3Index]); hostSVC != addr.SvcNone {154 l3 = hostSVC155 } else {156 l3 = addr.HostFromIPStr(parts[addrRegexpL3Index])157 if l3 == nil {158 return snet.SCIONAddress{},159 fmt.Errorf("invalid IP address string: %v", parts[addrRegexpL3Index])160 }161 }162 return snet.SCIONAddress{IA: ia, Host: l3}, nil163}...
udpConnection.go
Source:udpConnection.go
1// updConnection.2package connections3import (4 "net"5 "strconv"6 "github.com/shunhui19/goes/lib"7 "github.com/shunhui19/goes/protocols"8)9// UDPConnection struct.10type UDPConnection struct {11 baseConnection BaseConnection12 // Protocol Application layer protocol.13 Protocol protocols.Protocol14 // socket udp socket.15 socket net.PacketConn16 // remoteAddress remote address.17 remoteAddress net.Addr18}19// Send send data on the connection.20// if return true indicate message send success, otherwise return false indicate send fail.21// return nil indicate no data to send.22func (u *UDPConnection) Send(buffer string, raw bool) interface{} {23 if raw == false && u.Protocol != nil {24 switch result := u.Protocol.Encode([]byte(buffer)).(type) {25 case []byte:26 buffer = string(result)27 case string:28 buffer = result29 }30 if len(buffer) == 0 {31 return nil32 }33 }34 n, err := (u.socket).WriteTo([]byte(buffer), u.remoteAddress)35 if err != nil {36 lib.Warn("udp write to client error:", err)37 return false38 }39 return len(buffer) == n40}41// Close close connection.42func (u *UDPConnection) Close(data string) {43 if len(data) != 0 {44 u.Send(data, false)45 }46 err := u.socket.Close()47 if err != nil {48 lib.Warn(err.Error())49 }50}51// GetRemoteIP get remote ip.52func (u *UDPConnection) GetRemoteIP() string {53 IP, _, _ := net.SplitHostPort(u.remoteAddress.String())54 return IP55}56// GetRemotePort get remote port.57func (u *UDPConnection) GetRemotePort() int {58 _, port, _ := net.SplitHostPort(u.remoteAddress.String())59 p, _ := strconv.Atoi(port)60 return p61}62// GetRemoteAddress get remote address, the format is like this 127.0.0.1:8080.63func (u *UDPConnection) GetRemoteAddress() string {64 return u.remoteAddress.String()65}66// GetLocalIP get local ip.67func (u *UDPConnection) GetLocalIP() string {68 IP, _, _ := net.SplitHostPort((u.socket).LocalAddr().String())69 return IP70}71// GetLocalPort get local port.72func (u *UDPConnection) GetLocalPort() int {73 _, port, _ := net.SplitHostPort((u.socket).LocalAddr().String())74 p, _ := strconv.Atoi(port)75 return p76}77// GetLocalAddress get remote address, the format is like this http://127.0.0.1:8080.78func (u *UDPConnection) GetLocalAddress() string {79 return (u.socket).LocalAddr().String()80}81// AddRequestCount increase request record.82func (u *UDPConnection) AddRequestCount() {83 u.baseConnection.TotalRequest++84}85// NewUDPConnection new a object of UDPConnection.86func NewUDPConnection(socket net.PacketConn, remoteAddr net.Addr) *UDPConnection {87 udp := &UDPConnection{}88 udp.socket = socket89 udp.remoteAddress = remoteAddr90 return udp91}...
raw.go
Source:raw.go
...33 },34 }, nil35}36func rawBRIntfTopoBRAddr(i *jsontopo.BRInterface) (*net.UDPAddr, error) {37 rh, port, err := splitHostPort(i.Underlay.Public)38 if err != nil {39 return nil, err40 }41 var rawIP string42 if i.Underlay.Bind != "" {43 rawIP = i.Underlay.Bind44 } else if rh != "" {45 rawIP = rh46 } else {47 return nil, serrors.WithCtx(errUnderlayAddrNotFound, "underlay", i.Underlay)48 }49 return resolveToUDPAddr(rawIP, port)50}51func splitHostPort(rawAddr string) (string, int, error) {52 rh, rp, err := net.SplitHostPort(rawAddr)53 if err != nil {54 return "", 0, serrors.WrapStr("failed to split host port", err)55 }56 port, err := strconv.Atoi(rp)57 if err != nil {58 return "", 0, serrors.WrapStr("failed to parse port", err)59 }60 return rh, port, nil61}62func resolveToUDPAddr(rawIP string, port int) (*net.UDPAddr, error) {63 ipAddr, err := net.ResolveIPAddr("ip", rawIP)64 if err != nil {65 return nil, serrors.WrapStr("failed to resolve ip", err, "raw", rawIP)66 }67 if ipAddr.IP == nil {68 return nil, serrors.New("missing/invalid IP", "raw", rawIP)69 }70 // Convert to 4-byte format to simplify testing71 if ip4 := ipAddr.IP.To4(); ip4 != nil {72 ipAddr.IP = ip473 }74 return &net.UDPAddr{75 IP: append(ipAddr.IP[:0:0], ipAddr.IP...),76 Port: port,77 Zone: ipAddr.Zone,78 }, nil79}80func rawAddrToUDPAddr(rawAddr string) (*net.UDPAddr, error) {81 rh, port, err := splitHostPort(rawAddr)82 if err != nil {83 return nil, err84 }85 return resolveToUDPAddr(rh, port)86}
splitHostPort
Using AI Code Generation
1import (2func main() {3 host, port, err := net.SplitHostPort("www.google.com:80")4 if err != nil {5 fmt.Println(err)6 } else {7 fmt.Println(host)8 fmt.Println(port)9 }10}
splitHostPort
Using AI Code Generation
1import (2func main() {3 host, port, err := net.SplitHostPort("www.google.com:80")4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println(host, port)8}9func SplitHostPort(hostport string) (host, port string, err error)10import (11func main() {12 host, port, err := net.SplitHostPort("www.google.com:80")13 if err != nil {14 fmt.Println(err)15 }16 fmt.Println(host, port)17}18Recommended Posts: Golang | net.LookupIP() method19Golang | net.LookupHost() method20Golang | net.LookupCNAME() method21Golang | net.LookupNS() method22Golang | net.LookupMX() method23Golang | net.LookupSRV() method24Golang | net.LookupTXT() method25Golang | net.ParseIP() method26Golang | net.ParseCIDR() method27Golang | net.ParseMAC() method28Golang | net.JoinHostPort() method29Golang | net.JoinHostPort() method30Golang | net.Dial() method31Golang | net.DialTimeout() method32Golang | net.DialTCP() method33Golang | net.DialUDP() method34Golang | net.Listen() method35Golang | net.ListenTCP() method36Golang | net.ListenUDP() method37Golang | net.ListenPacket() method38Golang | net.ListenUnix() method39Golang | net.ListenUnixgram() method40Golang | net.DialUnix() method41Golang | net.DialUnixgram() method42Golang | net.ParseIP() method43Golang | net.ParseCIDR() method44Golang | net.ParseMAC() method
splitHostPort
Using AI Code Generation
1import (2func main() {3 host, port, err := net.SplitHostPort("localhost:8080")4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println("Host: ", host)8 fmt.Println("Port: ", port)9}
splitHostPort
Using AI Code Generation
1import (2func main() {3 host, port, err := net.SplitHostPort("www.google.com:80")4 if err != nil {5 fmt.Println("Error: ", err)6 }7 fmt.Println("Host is ", host)8 fmt.Println("Port is ", port)9}10Related Posts: How to split a string in Go (Golang)11How to get the current working directory in Go (Golang)12How to get the absolute path of a file in Go (Golang)13How to get the current date and time in Go (Golang)14How to get the current user in Go (Golang)15How to get the current user's home directory in Go (Golang)16How to get the current user's username in Go (Golang)17How to get the current user's shell in Go (Golang)18How to get the current user's UID in Go (Golang)19How to get the current user's GID in Go (Golang)20How to get the current user's groups in Go (Golang)21How to get the current user's group IDs in Go (Golang)22How to get the current user's group names in Go (Golang)23How to get the current user's groups in Go (Golang)24How to get the current user's group IDs in Go (Golang)25How to get the current user's group names in Go (Golang)26How to get the current user's groups in Go (Golang)27How to get the current user's group IDs in Go (Golang)28How to get the current user's group names in Go (Golang)29How to get the current user's groups in Go (Golang)30How to get the current user's group IDs in Go (Golang)31How to get the current user's group names in Go (Golang)32How to get the current user's groups in Go (Golang)33How to get the current user's group IDs in Go (Golang)34How to get the current user's group names in Go (Golang)35How to get the current user's groups in Go (Golang)36How to get the current user's group IDs in Go (Golang)37How to get the current user's group names in Go (Golang)
splitHostPort
Using AI Code Generation
1import (2func main() {3 host, port, err := net.SplitHostPort("localhost:8080")4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println(host)8 fmt.Println(port)9}10import (11func main() {12 addr := net.JoinHostPort(host, port)13 fmt.Println(addr)14}15import (16func main() {17 ips, err := net.LookupHost("localhost")18 if err != nil {19 fmt.Println(err)20 }21 fmt.Println(ips)22}
splitHostPort
Using AI Code Generation
1import (2func main() {3 host, port, err := net.SplitHostPort("www.google.com:80")4 fmt.Println(host, port, err)5}6import (7func main() {8 host, port, err := net.SplitHostPort("www.google.com:80")9 fmt.Println(host, port, err)10}11import (12func main() {13 host, port, err := net.SplitHostPort("
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!