Example #1
0
func tcpClient(addr string, key, message []byte) ([]byte, error) {
	tcpaddr, err := net.ResolveTCPAddr("tcp", addr)
	if err != nil {
		return nil, err
	}

	ciphertext, err := libsodium.EncryptData(key, message)
	if err != nil {
		return nil, err
	}

	tcpconn, err := net.DialTCP("tcp", nil, tcpaddr)
	if err != nil {
		return nil, err
	}
	defer tcpconn.Close()

	tcpconn.SetWriteDeadline(time.Now().Add(time.Duration(20) * time.Second))
	_, err = tcpconn.Write(netstring.Marshall(ciphertext))
	if err != nil {
		return nil, err
	}

	tcpconn.SetReadDeadline(time.Now().Add(time.Duration(20) * time.Second))
	bufReader := bufio.NewReader(tcpconn)
	var buf bytes.Buffer
	var ip []byte
	for {
		rData, err := bufReader.ReadBytes(',')
		if err != nil {
			if err == io.EOF {
				return nil, err
			}
			buf.Write(rData)
			continue
		}
		buf.Write(rData)
		ip, err = netstring.Unmarshall(buf.Bytes())
		if err != nil {
			if err == netstring.ErrNsLenNotEqaulOrgLen {
				continue
			}
			return nil, err
		}
		break
	}
	return ip, nil
}
Example #2
0
func udpClient(addr string, key, message []byte) error {
	udpaddr, err := net.ResolveUDPAddr("udp", addr)
	if err != nil {
		return err
	}

	ciphertext, err := libsodium.EncryptData(key, message)
	if err != nil {
		return err
	}

	udpconn, err := net.DialUDP("udp", nil, udpaddr)
	if err != nil {
		return err
	}
	defer udpconn.Close()

	_, err = udpconn.Write(netstring.Marshall(ciphertext))
	if err != nil {
		return err
	}

	return nil
}