|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function parseDestinationIP(packet) { |
|
|
|
|
|
const headerLength = (packet[0] & 0x0F) * 4; |
|
|
|
|
|
|
|
|
if (packet.length < headerLength + 4) { |
|
|
throw new Error('数据包太短,无法解析目标 IP'); |
|
|
} |
|
|
|
|
|
|
|
|
const destIP = `${packet[16]}.${packet[17]}.${packet[18]}.${packet[19]}`; |
|
|
return destIP; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function parseDestinationPort(packet) { |
|
|
|
|
|
const headerLength = (packet[0] & 0x0F) * 4; |
|
|
|
|
|
|
|
|
const protocol = packet[9]; |
|
|
|
|
|
|
|
|
if (protocol === 6 || protocol === 17) { |
|
|
|
|
|
if (packet.length < headerLength + 4) { |
|
|
throw new Error('数据包太短,无法解析目标端口'); |
|
|
} |
|
|
|
|
|
|
|
|
const destPort = (packet[headerLength + 2] << 8) + packet[headerLength + 3]; |
|
|
return destPort; |
|
|
} |
|
|
|
|
|
|
|
|
return 0; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function isValidIPv4Packet(packet) { |
|
|
|
|
|
if (!packet || packet.length < 20) { |
|
|
return false; |
|
|
} |
|
|
|
|
|
|
|
|
const version = (packet[0] >> 4) & 0x0F; |
|
|
if (version !== 4) { |
|
|
return false; |
|
|
} |
|
|
|
|
|
|
|
|
const headerLength = (packet[0] & 0x0F) * 4; |
|
|
if (headerLength < 20 || headerLength > packet.length) { |
|
|
return false; |
|
|
} |
|
|
|
|
|
return true; |
|
|
} |
|
|
|
|
|
module.exports = { |
|
|
parseDestinationIP, |
|
|
parseDestinationPort, |
|
|
isValidIPv4Packet |
|
|
}; |