读取文件tcp/udp/icmp校验和计算的c代码
时间: 2023-05-17 13:02:37 浏览: 185
IP/TCP/UDP checksum计算c代码
以下是一个简单的C代码,用于读取文件并计算TCP/UDP/ICMP校验和:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/ip_icmp.h>
unsigned short calculate_checksum(unsigned short *ptr, int nbytes);
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
FILE *fp = fopen(argv[1], "rb");
if (fp == NULL) {
printf("Error: cannot open file %s\n", argv[1]);
return 1;
}
unsigned char buffer[65536];
int total_size = 0;
while (!feof(fp)) {
int read_size = fread(buffer + total_size, 1, sizeof(buffer) - total_size, fp);
if (read_size <= 0) {
break;
}
total_size += read_size;
}
fclose(fp);
struct iphdr *ip_header = (struct iphdr *) buffer;
int ip_header_size = ip_header->ihl * 4;
if (ip_header->protocol == IPPROTO_TCP) {
struct tcphdr *tcp_header = (struct tcphdr *) (buffer + ip_header_size);
tcp_header->check = 0;
tcp_header->check = calculate_checksum((unsigned short *) tcp_header, ntohs(ip_header->tot_len) - ip_header_size);
printf("TCP checksum: 0x%04x\n", tcp_header->check);
} else if (ip_header->protocol == IPPROTO_UDP) {
struct udphdr *udp_header = (struct udphdr *) (buffer + ip_header_size);
udp_header->check = 0;
udp_header->check = calculate_checksum((unsigned short *) udp_header, ntohs(ip_header->tot_len) - ip_header_size);
printf("UDP checksum: 0x%04x\n", udp_header->check);
} else if (ip_header->protocol == IPPROTO_ICMP) {
struct icmphdr *icmp_header = (struct icmphdr *) (buffer + ip_header_size);
icmp_header->checksum = 0;
icmp_header->checksum = calculate_checksum((unsigned short *) icmp_header, ntohs(ip_header->tot_len) - ip_header_size);
printf("ICMP checksum: 0x%04x\n", icmp_header->checksum);
} else {
printf("Error: unsupported protocol %d\n", ip_header->protocol);
return 1;
}
return 0;
}
unsigned short calculate_checksum(unsigned short *ptr, int nbytes) {
unsigned long sum = 0;
while (nbytes > 1) {
sum += *ptr++;
nbytes -= 2;
}
if (nbytes == 1) {
sum += *(unsigned char *) ptr;
}
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
return (unsigned short) ~sum;
}
阅读全文