Skip to content

Instantly share code, notes, and snippets.

@calmh
Created November 29, 2016 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calmh/08831640543c961cd2c02020548451ca to your computer and use it in GitHub Desktop.
Save calmh/08831640543c961cd2c02020548451ca to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"bytes"
"encoding/hex"
"flag"
"fmt"
"io"
"net"
"os"
)
func main() {
flag.Parse()
// Read the hexdump from Stdin
bs, err := readHexDump(os.Stdin)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// "Dial" the destination
conn, err := net.Dial("udp", flag.Arg(0))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer conn.Close()
// Send the packet
if _, err := conn.Write(bs); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func readHexDump(r io.Reader) ([]byte, error) {
space := []byte{' '}
var hexBytes []byte
sc := bufio.NewScanner(r)
for sc.Scan() {
line := sc.Bytes()
firstSpace := bytes.Index(line, space)
if firstSpace > 2 {
// Line starts with something that is not a byte, it is probably
// an offset. Strip it.
line = line[firstSpace:]
}
hexBytes = append(hexBytes, bytes.Replace(line, space, nil, -1)...)
}
// Decode the hex data.
dst := make([]byte, hex.DecodedLen(len(hexBytes)))
if _, err := hex.Decode(dst, hexBytes); err != nil {
return nil, err
}
return dst, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment