本文整理汇总了Golang中golang.org/x/net/icmp.ParseMessage函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseMessage函数的具体用法?Golang ParseMessage怎么用?Golang ParseMessage使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ParseMessage函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Run
func (self *HikarianIcmp) Run() {
if self.mode == "decrypt" {
clientConn, err := icmp.ListenPacket("ip4:icmp", "0.0.0.0")
if err != nil {
log.Fatal(err)
}
defer clientConn.Close()
for {
buf := make([]byte, 1024)
nr, caddr, err := clientConn.ReadFrom(buf)
request, err := icmp.ParseMessage(ProtocolICMP, buf)
if err != nil {
log.Println("parse icmp request error: ", err.Error())
return
}
if request.Code == 0 {
return
}
body, err := request.Body.Marshal(ProtocolICMP)
if err != nil {
log.Println("marshal body error: ", err.Error())
continue
}
hash := binary.BigEndian.Uint16(body[0:2]) + binary.BigEndian.Uint16(body[2:4])
dataChannel := self.DataChannelPool.Get(hash)
if dataChannel == nil {
dataChannel = make(chan []byte)
self.DataChannelPool.Set(hash, dataChannel)
go self.transportServer(clientConn, caddr, dataChannel)
}
if request.Code == MagicCode {
log.Println("receive magic")
dataChannel <- body[:nr-4]
}
}
} else if self.mode == "encrypt" {
client, err := net.ResolveTCPAddr("tcp", self.client)
if err != nil {
log.Fatalln("resolve client address error: ", err.Error())
}
l, err := net.ListenTCP("tcp", client)
if err != nil {
log.Fatal(err)
}
defer l.Close()
for {
clientConn, err := l.AcceptTCP()
if err != nil {
log.Println("accept error: ", err.Error())
continue
}
defer clientConn.Close()
go self.transportClient(clientConn)
}
}
}
示例2: sleepMonitor
// Monitor clients going in/out of sleep mode via ICMP unreachable packets.
func sleepMonitor() {
c, err := icmp.ListenPacket("ip4:icmp", "0.0.0.0")
if err != nil {
log.Printf("error listening for udp - sending data to all ports for all connected clients. err: %s", err)
return
}
go icmpEchoSender(c)
defer c.Close()
for {
buf := make([]byte, 1500)
n, peer, err := c.ReadFrom(buf)
if err != nil {
log.Printf("%s\n", err.Error())
continue
}
msg, err := icmp.ParseMessage(1, buf[:n])
if err != nil {
continue
}
ip := peer.String()
// Look for echo replies, mark it as received.
if msg.Type == ipv4.ICMPTypeEchoReply {
pingResponse[ip] = stratuxClock.Time
continue // No further processing needed.
}
// Only deal with ICMP Unreachable packets (since that's what iOS and Android seem to be sending whenever the apps are not available).
if msg.Type != ipv4.ICMPTypeDestinationUnreachable {
continue
}
// Packet parsing.
mb, err := msg.Body.Marshal(1)
if err != nil {
continue
}
if len(mb) < 28 {
continue
}
// The unreachable port.
port := (uint16(mb[26]) << 8) | uint16(mb[27])
ipAndPort := ip + ":" + strconv.Itoa(int(port))
netMutex.Lock()
p, ok := outSockets[ipAndPort]
if !ok {
// Can't do anything, the client isn't even technically connected.
netMutex.Unlock()
continue
}
p.LastUnreachable = stratuxClock.Time
outSockets[ipAndPort] = p
netMutex.Unlock()
}
}
示例3: processPacket
func (p *Pinger) processPacket(recv *packet) error {
var bytes []byte
var proto int
if p.ipv4 {
if p.network == "ip" {
bytes = ipv4Payload(recv.bytes)
} else {
bytes = recv.bytes
}
proto = protocolICMP
} else {
bytes = recv.bytes
proto = protocolIPv6ICMP
}
var m *icmp.Message
var err error
if m, err = icmp.ParseMessage(proto, bytes[:recv.nbytes]); err != nil {
return fmt.Errorf("Error parsing icmp message")
}
if m.Type != ipv4.ICMPTypeEchoReply && m.Type != ipv6.ICMPTypeEchoReply {
// Not an echo reply, ignore it
return nil
}
outPkt := &Packet{
Nbytes: recv.nbytes,
IPAddr: p.ipaddr,
}
switch pkt := m.Body.(type) {
case *icmp.Echo:
outPkt.Rtt = time.Since(bytesToTime(pkt.Data[:timeSliceLength]))
outPkt.Seq = pkt.Seq
p.PacketsRecv += 1
default:
// Very bad, not sure how this can happen
return fmt.Errorf("Error, invalid ICMP echo reply. Body type: %T, %s",
pkt, pkt)
}
p.rtts = append(p.rtts, outPkt.Rtt)
handler := p.OnRecv
if handler != nil {
handler(outPkt)
}
return nil
}
示例4: main
func main() {
timeout := 5
t1 := time.Now()
c, err := icmp.ListenPacket("ip4:icmp", "0.0.0.0")
if err != nil {
checkError(err, "listen err, ")
}
c.SetDeadline(t1.Add(time.Second * time.Duration(timeout)))
defer c.Close()
wm := icmp.Message{
Type: ipv4.ICMPTypeEcho, Code: 0,
Body: &icmp.Echo{
ID: os.Getpid() & 0xffff, Seq: 1,
Data: []byte("HELLO-R-U-THERE"),
},
}
wb, err := wm.Marshal(nil)
if err != nil {
log.Fatal(err)
}
// Send ICMP echo and start timer
starttime := time.Now()
if _, err := c.WriteTo(wb, &net.IPAddr{IP: net.ParseIP(targetIP)}); err != nil {
log.Fatalf("WriteTo err, %s", err)
}
rb := make([]byte, 1500)
// Look for ICMP response and stop time
n, peer, err := c.ReadFrom(rb)
stoptime := time.Now()
if err != nil {
log.Fatal(err)
}
//rm, err := icmp.ParseMessage(iana.ProtocolICMP, rb[:n])
rm, err := icmp.ParseMessage(1, rb[:n])
if err != nil {
log.Fatal(err)
}
switch rm.Type {
case ipv4.ICMPTypeEchoReply:
log.Printf("got reflection from %v", peer)
log.Printf("ICMP echo request sent on ", starttime)
log.Printf("ICMP echo response received on ", stoptime)
default:
log.Printf("got %+v; want echo reply", rm)
}
}
示例5: ping
func ping(listener *icmp.PacketConn, message icmp.Message, raddr net.Addr, timeout time.Duration) (Pong, error) {
data, err := message.Marshal(nil)
if err != nil {
return Pong{}, err
}
_, err = listener.WriteTo(data, raddr)
if err != nil {
return Pong{}, err
}
now := time.Now()
done := make(chan Pong)
go func() {
for {
buf := make([]byte, 10000)
// bufio
n, peer, err := listener.ReadFrom(buf)
if err != nil {
return
}
since := time.Since(now)
input, err := icmp.ParseMessage(protocolICMP, buf[:n])
if err != nil {
return
}
if input.Type != ipv4.ICMPTypeEchoReply {
continue
}
echo := input.Body.(*icmp.Echo)
pong := Pong{
Peer: peer,
ID: echo.ID,
Seq: echo.Seq,
Data: echo.Data,
Size: n,
RTT: since,
}
done <- pong
return
}
}()
select {
case pong := <-done:
return pong, nil
case <-time.After(timeout):
return Pong{}, errors.New("Timeout")
}
}
示例6: ExamplePacketConn_nonPrivilegedPing
func ExamplePacketConn_nonPrivilegedPing() {
switch runtime.GOOS {
case "darwin":
case "linux":
log.Println("you may need to adjust the net.ipv4.ping_group_range kernel state")
default:
log.Println("not supported on", runtime.GOOS)
return
}
c, err := icmp.ListenPacket("udp6", "fe80::1%en0")
if err != nil {
log.Fatal(err)
}
defer c.Close()
wm := icmp.Message{
Type: ipv6.ICMPTypeEchoRequest, Code: 0,
Body: &icmp.Echo{
ID: os.Getpid() & 0xffff, Seq: 1,
Data: []byte("HELLO-R-U-THERE"),
},
}
wb, err := wm.Marshal(nil)
if err != nil {
log.Fatal(err)
}
if _, err := c.WriteTo(wb, &net.UDPAddr{IP: net.ParseIP("ff02::1"), Zone: "en0"}); err != nil {
log.Fatal(err)
}
rb := make([]byte, 1500)
n, peer, err := c.ReadFrom(rb)
if err != nil {
log.Fatal(err)
}
rm, err := icmp.ParseMessage(58, rb[:n])
if err != nil {
log.Fatal(err)
}
switch rm.Type {
case ipv6.ICMPTypeEchoReply:
log.Printf("got reflection from %v", peer)
default:
log.Printf("got %+v; want echo reply", rm)
}
}
示例7: testDNS
// This checks if we can convert an URL to an IP
func testDNS(pr *pingResponse, pi pingInfo, conn *icmp.PacketConn) {
start := time.Now()
msg := createMessage()
msg_bytes, err := msg.Marshal(nil)
if err != nil {
emsg := "Could not marshal the message to []byte."
logger.WriteString(emsg)
pr.err = errors.New(emsg)
return
}
ip, _ := net.LookupHost(pi.externalurl)
if _, err := conn.WriteTo(msg_bytes, &net.UDPAddr{IP: net.ParseIP(ip[0]), Zone: "en0"}); err != nil {
emsg := "Could not write to the internal ip address: " + ip[0]
logger.WriteString(emsg)
pr.external_url = false
pr.err = errors.New(emsg)
return
}
pr.external_url = true
response := make([]byte, 1500)
count, peer, err := conn.ReadFrom(response)
if err != nil {
emsg := "Could not read the response."
logger.WriteString(emsg)
pr.external_url = false
pr.err = errors.New(emsg)
return
}
_, err = icmp.ParseMessage(protocolICMP, response[:count])
if err != nil {
emsg := "Could not parse the message received."
logger.WriteString(emsg)
pr.external_url = false
pr.err = errors.New(emsg)
return
}
logger.WriteString("Response " + strconv.Itoa(sequence) + " received from " + peer.String() +
" after " + time.Now().Sub(start).String())
}
示例8: TestMarshalAndParseMessageForIPv4
func TestMarshalAndParseMessageForIPv4(t *testing.T) {
for i, tt := range marshalAndParseMessageForIPv4Tests {
b, err := tt.Marshal(nil)
if err != nil {
t.Fatal(err)
}
m, err := icmp.ParseMessage(iana.ProtocolICMP, b)
if err != nil {
t.Fatal(err)
}
if m.Type != tt.Type || m.Code != tt.Code {
t.Errorf("#%v: got %v; want %v", i, m, &tt)
}
if !reflect.DeepEqual(m.Body, tt.Body) {
t.Errorf("#%v: got %v; want %v", i, m.Body, tt.Body)
}
}
}
示例9: TestMarshalAndParseMultipartMessageForIPv4
func TestMarshalAndParseMultipartMessageForIPv4(t *testing.T) {
for i, tt := range marshalAndParseMultipartMessageForIPv4Tests {
b, err := tt.Marshal(nil)
if err != nil {
t.Fatal(err)
}
if b[5] != 32 {
t.Errorf("#%v: got %v; want 32", i, b[5])
}
m, err := icmp.ParseMessage(iana.ProtocolICMP, b)
if err != nil {
t.Fatal(err)
}
if m.Type != tt.Type || m.Code != tt.Code {
t.Errorf("#%v: got %v; want %v", i, m, &tt)
}
switch m.Type {
case ipv4.ICMPTypeDestinationUnreachable:
got, want := m.Body.(*icmp.DstUnreach), tt.Body.(*icmp.DstUnreach)
if !reflect.DeepEqual(got.Extensions, want.Extensions) {
t.Error(dumpExtensions(i, got.Extensions, want.Extensions))
}
if len(got.Data) != 128 {
t.Errorf("#%v: got %v; want 128", i, len(got.Data))
}
case ipv4.ICMPTypeTimeExceeded:
got, want := m.Body.(*icmp.TimeExceeded), tt.Body.(*icmp.TimeExceeded)
if !reflect.DeepEqual(got.Extensions, want.Extensions) {
t.Error(dumpExtensions(i, got.Extensions, want.Extensions))
}
if len(got.Data) != 128 {
t.Errorf("#%v: got %v; want 128", i, len(got.Data))
}
case ipv4.ICMPTypeParameterProblem:
got, want := m.Body.(*icmp.ParamProb), tt.Body.(*icmp.ParamProb)
if !reflect.DeepEqual(got.Extensions, want.Extensions) {
t.Error(dumpExtensions(i, got.Extensions, want.Extensions))
}
if len(got.Data) != 128 {
t.Errorf("#%v: got %v; want 128", i, len(got.Data))
}
}
}
}
示例10: Read
func (i *ICMP) Read() ([]byte, error) {
buf := make([]byte, 10000)
n, _, err := i.listener.ReadFrom(buf)
if err != nil {
return nil, err
}
input, err := icmp.ParseMessage(_PROTOCOL_ICMP, buf[:n])
if err != nil {
return nil, err
}
if input.Type != ipv4.ICMPTypeEchoReply {
return nil, nil
}
echo, ok := input.Body.(*icmp.Echo)
if !ok {
return nil, nil
}
return echo.Data, nil
}
示例11: TestMarshalAndParseMessageForIPv6
func TestMarshalAndParseMessageForIPv6(t *testing.T) {
pshicmp := icmp.IPv6PseudoHeader(net.ParseIP("fe80::1"), net.ParseIP("ff02::1"))
for i, tt := range marshalAndParseMessageForIPv6Tests {
for _, psh := range [][]byte{pshicmp, nil} {
b, err := tt.Marshal(psh)
if err != nil {
t.Fatal(err)
}
m, err := icmp.ParseMessage(iana.ProtocolIPv6ICMP, b)
if err != nil {
t.Fatal(err)
}
if m.Type != tt.Type || m.Code != tt.Code {
t.Errorf("#%v: got %v; want %v", i, m, &tt)
}
if !reflect.DeepEqual(m.Body, tt.Body) {
t.Errorf("#%v: got %v; want %v", i, m.Body, tt.Body)
}
}
}
}
示例12: TestMarshalAndParseMultipartMessageForIPv6
func TestMarshalAndParseMultipartMessageForIPv6(t *testing.T) {
pshicmp := icmp.IPv6PseudoHeader(net.ParseIP("fe80::1"), net.ParseIP("ff02::1"))
for i, tt := range marshalAndParseMultipartMessageForIPv6Tests {
for _, psh := range [][]byte{pshicmp, nil} {
b, err := tt.Marshal(psh)
if err != nil {
t.Fatal(err)
}
if b[4] != 16 {
t.Errorf("#%v: got %v; want 16", i, b[4])
}
m, err := icmp.ParseMessage(iana.ProtocolIPv6ICMP, b)
if err != nil {
t.Fatal(err)
}
if m.Type != tt.Type || m.Code != tt.Code {
t.Errorf("#%v: got %v; want %v", i, m, &tt)
}
switch m.Type {
case ipv6.ICMPTypeDestinationUnreachable:
got, want := m.Body.(*icmp.DstUnreach), tt.Body.(*icmp.DstUnreach)
if !reflect.DeepEqual(got.Extensions, want.Extensions) {
t.Error(dumpExtensions(i, got.Extensions, want.Extensions))
}
if len(got.Data) != 128 {
t.Errorf("#%v: got %v; want 128", i, len(got.Data))
}
case ipv6.ICMPTypeTimeExceeded:
got, want := m.Body.(*icmp.TimeExceeded), tt.Body.(*icmp.TimeExceeded)
if !reflect.DeepEqual(got.Extensions, want.Extensions) {
t.Error(dumpExtensions(i, got.Extensions, want.Extensions))
}
if len(got.Data) != 128 {
t.Errorf("#%v: got %v; want 128", i, len(got.Data))
}
}
}
}
}
示例13: ExamplePacketConn_nonPrivilegedPing
func ExamplePacketConn_nonPrivilegedPing() {
c, err := icmp.ListenPacket("udp6", "fe80::1%en0")
if err != nil {
log.Fatal(err)
}
defer c.Close()
wm := icmp.Message{
Type: ipv6.ICMPTypeEchoRequest, Code: 0,
Body: &icmp.Echo{
ID: os.Getpid() & 0xffff, Seq: 1,
Data: []byte("HELLO-R-U-THERE"),
},
}
wb, err := wm.Marshal(nil)
if err != nil {
log.Fatal(err)
}
if _, err := c.WriteTo(wb, &net.UDPAddr{IP: net.ParseIP("ff02::1"), Zone: "en0"}); err != nil {
log.Fatal(err)
}
rb := make([]byte, 1500)
n, peer, err := c.ReadFrom(rb)
if err != nil {
log.Fatal(err)
}
rm, err := icmp.ParseMessage(iana.ProtocolIPv6ICMP, rb[:n])
if err != nil {
log.Fatal(err)
}
switch rm.Type {
case ipv6.ICMPTypeEchoReply:
log.Printf("got reflection from %v", peer)
default:
log.Printf("got %+v; want echo reply", rm)
}
}
示例14: parseMessage
func (p *Ping) parseMessage(r Reply, ssmap map[int]int64) bool {
stop := time.Now().UnixNano()
rep, err := icmp.ParseMessage(iana.ProtocolICMP, r.bytes)
if err != nil {
fmt.Printf("* Reply error from %s: icmp_seq=%d -> %s\n", r.addr, p.sends, r.bytes)
return false
}
var seq int
switch pkt := rep.Body.(type) {
case *icmp.Echo:
if !(pkt.ID == p.id && pkt.Seq <= p.sends && bytes.Equal(pkt.Data, p.data)) {
fmt.Printf("* Wrong data %d bytes from %s (ID=[%d,%d], Seq=[%d,%d]): icmp_seq=%d\n",
r.size, r.addr, pkt.ID, p.id, pkt.Seq, p.sends, p.sends)
return false
}
seq = pkt.Seq
default:
fmt.Printf("* Not echo received from %s: icmp_seq=%d\n", r.size, r.addr, p.sends)
return false
}
if v, ok := ssmap[seq]; !ok {
fmt.Printf("* Duplicated packet received from %s: icmp_seq=%d\n", r.addr, p.sends)
return false
} else {
rtt := stop - v
delete(ssmap, seq)
fmt.Printf("%d bytes from %s: icmp_seq=%d time=%.2f ms\n",
r.size, r.addr, p.sends, float64(rtt)/float64(time.Millisecond))
}
return true
}
示例15: procRecv
func (p *Pinger) procRecv(bytes []byte, ra net.Addr, ctx *context) {
var ipaddr *net.IPAddr
switch adr := ra.(type) {
case *net.IPAddr:
ipaddr = adr
case *net.UDPAddr:
ipaddr = &net.IPAddr{IP: adr.IP, Zone: adr.Zone}
default:
return
}
addr := ipaddr.String()
p.mu.Lock()
_, ok := p.addrs[addr]
p.mu.Unlock()
if !ok {
return
}
var proto int
if isIPv4(ipaddr.IP) {
if p.network == "ip" {
bytes = ipv4Payload(bytes)
}
proto = ProtocolICMP
} else if isIPv6(ipaddr.IP) {
proto = ProtocolIPv6ICMP
} else {
return
}
var m *icmp.Message
var err error
if m, err = icmp.ParseMessage(proto, bytes); err != nil {
return
}
if m.Type != ipv4.ICMPTypeEchoReply && m.Type != ipv6.ICMPTypeEchoReply {
return
}
var rtt time.Duration
switch pkt := m.Body.(type) {
case *icmp.Echo:
if pkt.ID == p.id && pkt.Seq == p.seq {
rtt = time.Since(bytesToTime(pkt.Data[:TimeSliceLength]))
}
default:
return
}
if 0 == rtt {
return
}
p.mu.Lock()
delete(p.sent, addr)
if len(p.sent) == 0 && !p.done {
p.done = true
close(ctx.done)
}
p.mu.Unlock()
if p.OnRecv != nil {
p.OnRecv(ipaddr, rtt)
}
}