github.com/google/cloudprober@v0.11.3/probes/ping/icmpconn_nonunix.go (about)

     1  // Copyright 2020 The Cloudprober Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  //go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris
    16  // +build !aix,!darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris
    17  
    18  package ping
    19  
    20  import (
    21  	"net"
    22  	"strconv"
    23  	"time"
    24  
    25  	"golang.org/x/net/icmp"
    26  )
    27  
    28  type icmpPacketConn struct {
    29  	c *icmp.PacketConn
    30  }
    31  
    32  func newICMPConn(sourceIP net.IP, ipVer int, datagramSocket bool) (icmpConn, error) {
    33  	network := map[int]string{
    34  		4: "ip4:icmp",
    35  		6: "ip6:ipv6-icmp",
    36  	}[ipVer]
    37  
    38  	if datagramSocket {
    39  		network = "udp" + strconv.Itoa(ipVer)
    40  	}
    41  
    42  	c, err := icmp.ListenPacket(network, sourceIP.String())
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	return &icmpPacketConn{c}, nil
    47  }
    48  
    49  func (ipc *icmpPacketConn) read(buf []byte) (int, net.Addr, time.Time, error) {
    50  	n, addr, err := ipc.c.ReadFrom(buf)
    51  	return n, addr, time.Now(), err
    52  }
    53  
    54  func (ipc *icmpPacketConn) write(buf []byte, peer net.Addr) (int, error) {
    55  	return ipc.c.WriteTo(buf, peer)
    56  }
    57  
    58  func (ipc *icmpPacketConn) setReadDeadline(deadline time.Time) {
    59  	ipc.c.SetReadDeadline(deadline)
    60  }
    61  
    62  func (ipc *icmpPacketConn) close() {
    63  	ipc.c.Close()
    64  }