You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
117 lines
2.7 KiB
Go
117 lines
2.7 KiB
Go
package tools
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"b612.me/starainrt"
|
|
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
var udpcmd = &cobra.Command{
|
|
Use: "udp",
|
|
Short: "发送并监听udp数据包",
|
|
Long: "发送并监听udp数据包",
|
|
Run: func(this *cobra.Command, args []string) {
|
|
if len(args) != 1 {
|
|
fmt.Println("请指定远程udp地址")
|
|
return
|
|
}
|
|
l, _ := this.Flags().GetString("lport")
|
|
p, _ := this.Flags().GetString("rport")
|
|
a, _ := this.Flags().GetString("laddr")
|
|
s, _ := this.Flags().GetBool("local")
|
|
b, _ := this.Flags().GetBool("byte")
|
|
laddr, err := net.ResolveUDPAddr("udp", a+":"+l)
|
|
raddr, err := net.ResolveUDPAddr("udp", args[0]+":"+p)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
if s {
|
|
udplisten, err := net.ListenUDP("udp", laddr)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
fmt.Println("监听已建立")
|
|
go func() {
|
|
for {
|
|
buf := make([]byte, 204800)
|
|
n, addr, err := udplisten.ReadFromUDP(buf)
|
|
if err != nil {
|
|
fmt.Printf("Error from %s Where Message=%s\n", addr.String(), err.Error())
|
|
continue
|
|
}
|
|
fmt.Printf("Receive Msg From %s : %s\n", addr.String(), string(buf[0:n]))
|
|
if b {
|
|
fmt.Println(buf[0:n])
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
myudp, err := net.DialUDP("udp", nil, raddr)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
fmt.Println("UDP虚拟连接已建立")
|
|
go func() {
|
|
var err error
|
|
for {
|
|
txt := starainrt.MessageBox("", "")
|
|
if txt == "" {
|
|
continue
|
|
}
|
|
if !b {
|
|
_, err = myudp.Write([]byte(txt))
|
|
} else {
|
|
var sendbyte []byte
|
|
bytes := strings.Split(txt, ",")
|
|
for _, v := range bytes {
|
|
ints, _ := strconv.Atoi(v)
|
|
if ints < 0 || ints > 255 {
|
|
continue
|
|
}
|
|
sendbyte = append(sendbyte, byte(ints))
|
|
}
|
|
_, err = myudp.Write(sendbyte)
|
|
}
|
|
if err != nil {
|
|
fmt.Printf("Error from %s Where Message=%s\n", myudp.RemoteAddr().String(), err.Error())
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
for {
|
|
buf := make([]byte, 204800)
|
|
n, err := myudp.Read(buf)
|
|
if err != nil {
|
|
fmt.Printf("Error from %s Where Message=%s\n", myudp.RemoteAddr().String(), err.Error())
|
|
return
|
|
}
|
|
|
|
fmt.Printf("Receive Msg From %s : %s\n", myudp.RemoteAddr().String(), string(buf[0:n]))
|
|
if b {
|
|
fmt.Println(buf[0:n])
|
|
}
|
|
}
|
|
},
|
|
}
|
|
|
|
/*
|
|
|
|
*/
|
|
|
|
func init() {
|
|
Maincmd.AddCommand(udpcmd)
|
|
udpcmd.Flags().BoolP("byte", "b", false, "发送二进制数据")
|
|
udpcmd.Flags().StringP("lport", "l", "1127", "本地监听端口")
|
|
udpcmd.Flags().StringP("rport", "p", "1127", "远程连接端口")
|
|
udpcmd.Flags().StringP("laddr", "a", "0.0.0.0", "本地监听ip")
|
|
udpcmd.Flags().BoolP("local", "s", false, "启动本地监听")
|
|
}
|