convert.go 687 Bytes
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
package multiaddr

import (
  "encoding/binary"
  "net"
  "strconv"
)

func AddressStringToBytes(p *Protocol, s string) []byte {
  switch p.Code {

  // ipv4,6
  case 4, 41:
    return net.ParseIP(s).To4()

  // tcp udp dccp sctp
  case 6, 17, 33, 132:
    b := make([]byte, 2)
    i, err := strconv.Atoi(s)
    if err == nil {
      binary.BigEndian.PutUint16(b, uint16(i))
    }
    return b
  }

  return []byte{}
}

func AddressBytesToString(p *Protocol, b []byte) string {
  switch p.Code {

  // ipv4,6
  case 4, 41:
    return net.IP(b).String()

  // tcp udp dccp sctp
  case 6, 17, 33, 132:
    i := binary.BigEndian.Uint16(b)
    return strconv.Itoa(int(i))
  }

  return ""
}