39 lines
1.5 KiB
Swift
39 lines
1.5 KiB
Swift
|
|
import Foundation
|
||
|
|
|
||
|
|
// A nonce in the payload binds a reply to this request. The kernel may rewrite
|
||
|
|
// the identifier on an unprivileged datagram ICMP socket.
|
||
|
|
enum ICMPEchoPacket {
|
||
|
|
static func checksum(_ bytes: [UInt8]) -> UInt16 {
|
||
|
|
var sum: UInt32 = 0
|
||
|
|
var index = 0
|
||
|
|
while index + 1 < bytes.count {
|
||
|
|
sum += (UInt32(bytes[index]) << 8) | UInt32(bytes[index + 1])
|
||
|
|
index += 2
|
||
|
|
}
|
||
|
|
if index < bytes.count { sum += UInt32(bytes[index]) << 8 }
|
||
|
|
while sum >> 16 != 0 { sum = (sum & 0xffff) + (sum >> 16) }
|
||
|
|
return ~UInt16(sum)
|
||
|
|
}
|
||
|
|
|
||
|
|
static func request(identifier: UInt16, payload: [UInt8]) -> [UInt8] {
|
||
|
|
var bytes: [UInt8] = [8, 0, 0, 0, UInt8(identifier >> 8), UInt8(identifier & 0xff), 0, 1]
|
||
|
|
bytes += payload
|
||
|
|
let value = checksum(bytes)
|
||
|
|
bytes[2] = UInt8(value >> 8)
|
||
|
|
bytes[3] = UInt8(value & 0xff)
|
||
|
|
return bytes
|
||
|
|
}
|
||
|
|
|
||
|
|
static func isReply(_ received: [UInt8], payload: [UInt8]) -> Bool {
|
||
|
|
var offset = 0
|
||
|
|
if let first = received.first, first >> 4 == 4 {
|
||
|
|
offset = Int(first & 0x0f) * 4
|
||
|
|
guard offset >= 20 else { return false }
|
||
|
|
}
|
||
|
|
guard received.count == offset + 8 + payload.count else { return false }
|
||
|
|
let reply = Array(received.dropFirst(offset))
|
||
|
|
return reply[0] == 0 && reply[1] == 0 && reply[6] == 0 && reply[7] == 1
|
||
|
|
&& Array(reply.dropFirst(8)) == payload && checksum(reply) == 0
|
||
|
|
}
|
||
|
|
}
|