1 //
2 // Copyright (C) 2013 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #ifndef SHILL_ICMP_H_
18 #define SHILL_ICMP_H_
19 
20 #if defined(__ANDROID__)
21 #include <linux/icmp.h>
22 #else
23 #include <netinet/ip_icmp.h>
24 #endif  // __ANDROID__
25 
26 #include <memory>
27 
28 #include <base/macros.h>
29 
30 namespace shill {
31 
32 class IPAddress;
33 class ScopedSocketCloser;
34 class Sockets;
35 
36 // The Icmp class encapsulates the task of sending ICMP frames.
37 class Icmp {
38  public:
39   static const int kIcmpEchoCode;
40 
41   Icmp();
42   virtual ~Icmp();
43 
44   // Create a socket for transmission of ICMP frames.
45   virtual bool Start();
46 
47   // Destroy the transmit socket.
48   virtual void Stop();
49 
50   // Returns whether an ICMP socket is open.
51   virtual bool IsStarted() const;
52 
53   // Send an ICMP Echo Request (Ping) packet to |destination|. The ID and
54   // sequence number fields of the echo request will be set to |id| and
55   // |seq_num| respectively.
56   virtual bool TransmitEchoRequest(const IPAddress& destination, uint16_t id,
57                                    uint16_t seq_num);
58 
socket()59   int socket() { return socket_; }
60 
61  private:
62   friend class IcmpTest;
63 
64   // Compute the checksum for Echo Request |hdr| of length |len| according to
65   // specifications in RFC 792.
66   static uint16_t ComputeIcmpChecksum(const struct icmphdr& hdr, size_t len);
67 
68   std::unique_ptr<Sockets> sockets_;
69   std::unique_ptr<ScopedSocketCloser> socket_closer_;
70   int socket_;
71 
72   DISALLOW_COPY_AND_ASSIGN(Icmp);
73 };
74 
75 }  // namespace shill
76 
77 #endif  // SHILL_ICMP_H_
78