afl-transmit/net/peer.go

56 lines
1.2 KiB
Go
Raw Normal View History

2020-06-19 13:31:20 +00:00
package net
import (
2020-06-20 17:07:58 +00:00
"fmt"
2020-06-19 13:31:20 +00:00
"log"
"net"
2020-06-20 17:07:58 +00:00
"regexp"
"strings"
)
var (
portSuffixRegex = regexp.MustCompile(":\\d{0,5}$")
2020-06-19 13:31:20 +00:00
)
type Peer struct {
Address string
}
2020-06-20 17:07:58 +00:00
// Creates a peer from the given address
func CreatePeer(address string) Peer {
// Clean line
address = strings.TrimSpace(address)
// Check if a port is already part of the address
// This is the lazy way: if a IPv6 literal is given without square brackets and without a port, this will fail badly.
if !portSuffixRegex.MatchString(address) {
// Port number is not yet part of the address, so append the default port number
address = fmt.Sprintf("%s:%d", address, ServerPort)
}
// Return constructed Peer
return Peer{
Address: address,
}
}
2020-06-19 13:31:20 +00:00
// Sends the given content to the peer
func (p *Peer) SendToPeer(content []byte) {
// Build up a connection
tcpConn, dialErr := net.Dial("tcp", p.Address)
if dialErr != nil {
log.Printf("Unable to connect to peer %s: %s", p.Address, dialErr)
return
}
// Send
_, writeErr := tcpConn.Write(content)
if writeErr != nil {
log.Printf("Unable to write to peer %s: %s", tcpConn.RemoteAddr().String(), writeErr)
return
}
// Close connection
tcpConn.Close()
}