Created
November 29, 2016 14:43
-
-
Save calmh/08831640543c961cd2c02020548451ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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