github.com/piotrnar/gocoin@v0.0.0-20240512203912-faa0448c5e96/lib/btc/netaddr.go (about)

     1  package btc
     2  
     3  import (
     4  	"fmt"
     5  	"encoding/binary"
     6  )
     7  
     8  type NetAddr struct {
     9  	Services uint64
    10  	Ip6 [12]byte
    11  	Ip4 [4]byte
    12  	Port uint16
    13  }
    14  
    15  func NewNetAddr(b []byte) (na *NetAddr) {
    16  	if len(b) != 26 {
    17  		println("Incorrect input data length", len(b))
    18  		return
    19  	}
    20  	na = new(NetAddr)
    21  	na.Services = binary.LittleEndian.Uint64(b[0:8])
    22  	copy(na.Ip6[:], b[8:20])
    23  	copy(na.Ip4[:], b[20:24])
    24  	na.Port = binary.BigEndian.Uint16(b[24:26])
    25  	return
    26  }
    27  
    28  func (a *NetAddr) Bytes() (res []byte) {
    29  	res = make([]byte, 26)
    30  	binary.LittleEndian.PutUint64(res[0:8], a.Services)
    31  	copy(res[8:20], a.Ip6[:])
    32  	copy(res[20:24], a.Ip4[:])
    33  	binary.BigEndian.PutUint16(res[24:26], a.Port)
    34  	return
    35  }
    36  
    37  
    38  func (a *NetAddr) String() string {
    39  	return fmt.Sprintf("%d.%d.%d.%d:%d", a.Ip4[0], a.Ip4[1], a.Ip4[2], a.Ip4[3], a.Port)
    40  }