Ver Fonte

x/net/{internal/icmp,ipv4,ipv6}: better method for icmp.Type interface

LGTM=iant
R=iant, bradfitz
CC=golang-codereviews
https://golang.org/cl/173670044
Mikio Hara há 11 anos atrás
pai
commit
e93b1edd55
3 ficheiros alterados com 20 adições e 6 exclusões
  1. 3 5
      internal/icmp/message.go
  2. 7 0
      ipv4/icmp.go
  3. 10 1
      ipv6/icmp.go

+ 3 - 5
internal/icmp/message.go

@@ -17,7 +17,7 @@ import (
 
 // A Type represents an ICMP message type.
 type Type interface {
-	String() string
+	Protocol() int
 }
 
 // A Message represents an ICMP message.
@@ -39,18 +39,16 @@ type Message struct {
 // When psh is not nil, it must be the pseudo header for IPv6.
 func (m *Message) Marshal(psh []byte) ([]byte, error) {
 	var mtype int
-	var icmpv6 bool
 	switch typ := m.Type.(type) {
 	case ipv4.ICMPType:
 		mtype = int(typ)
 	case ipv6.ICMPType:
 		mtype = int(typ)
-		icmpv6 = true
 	default:
 		return nil, errors.New("invalid argument")
 	}
 	b := []byte{byte(mtype), byte(m.Code), 0, 0}
-	if icmpv6 && psh != nil {
+	if m.Type.Protocol() == iana.ProtocolIPv6ICMP && psh != nil {
 		b = append(psh, b...)
 	}
 	if m.Body != nil && m.Body.Len() != 0 {
@@ -60,7 +58,7 @@ func (m *Message) Marshal(psh []byte) ([]byte, error) {
 		}
 		b = append(b, mb...)
 	}
-	if icmpv6 {
+	if m.Type.Protocol() == iana.ProtocolIPv6ICMP {
 		if psh == nil { // cannot calculate checksum here
 			return b, nil
 		}

+ 7 - 0
ipv4/icmp.go

@@ -4,6 +4,8 @@
 
 package ipv4
 
+import "golang.org/x/net/internal/iana"
+
 // An ICMPType represents a type of ICMP message.
 type ICMPType int
 
@@ -14,3 +16,8 @@ func (typ ICMPType) String() string {
 	}
 	return s
 }
+
+// Protocol returns the ICMPv4 protocol number.
+func (typ ICMPType) Protocol() int {
+	return iana.ProtocolICMP
+}

+ 10 - 1
ipv6/icmp.go

@@ -4,7 +4,11 @@
 
 package ipv6
 
-import "sync"
+import (
+	"sync"
+
+	"golang.org/x/net/internal/iana"
+)
 
 // An ICMPType represents a type of ICMP message.
 type ICMPType int
@@ -17,6 +21,11 @@ func (typ ICMPType) String() string {
 	return s
 }
 
+// Protocol returns the ICMPv6 protocol number.
+func (typ ICMPType) Protocol() int {
+	return iana.ProtocolIPv6ICMP
+}
+
 // An ICMPFilter represents an ICMP message filter for incoming
 // packets.
 type ICMPFilter struct {