【发布时间】:2017-10-31 13:20:52
【问题描述】:
因此,从 parseEther 方法调用 parseIP 函数时会发生分段错误。
我真的不知道为什么会出现分段错误,我只是在获取数据包指针并添加以太网标头的长度 (14)。
打印地址的输出为我提供了相隔 14 的十六进制地址,因此我知道指针指向内存中的正确位置。尽管如此,当我通过它时仍然会遇到分段错误?
我是否遗漏了一些非常明显的东西?
示例输出:
https://s1.postimg.org/96owsptn8v/seg_fault.png
编辑
我只是从 parseIP 中取出代码并将其放入调用它的 if 语句中,它工作得非常好。真的很奇怪。有人知道吗?
void parseIP(const unsigned char *packet)
{
printf("before we cast ip header");
struct ip *ip_header = (struct ip*) *packet;
printf("Before we initialise length");
short length = ip_header -> ip_len;
printf("Before we initialise headerlength");
int headerlength = ntohs(ip_header-> ip_hl); //iphdr points to header of network packet
printf("No segmentation fault here! \n");
printf("\n Source Ip address \n");
printf("%s", inet_ntoa(ip_header -> ip_src));
printf("\n Destination Ip address \n");
printf("%s", inet_ntoa(ip_header -> ip_dst));
int data_bytes = length - headerlength;
const unsigned char *payload = packet + headerlength;
}
void parseEther(const unsigned char *packet, int length)
{
int i;
int pcount = 0;
struct ether_header *eth_header = (struct ether_header *) packet;
printf("\n\n === PACKET %ld HEADER ===", pcount);
printf("\nSource MAC: ");
for (i = 0; i < 6; ++i)
{
printf("%02x", eth_header->ether_shost[i]);
if (i < 5)
{
printf(":");
}
}
printf("\nDestination MAC: ");
for (i = 0; i < 6; ++i)
{
printf("%02x", eth_header->ether_dhost[i]);
if (i < 5)
{
printf(":");
}
}
int data_bytes = length - ETH_HLEN;
printf(" \n total length - %d -- length of header - %d -- remaining length - %d \n", length, ETH_HLEN, data_bytes);
printf("Packet address - %p\n", packet);
const unsigned char *payload = packet + ETH_HLEN;
printf("Payload address - %p\n", payload);
//payload pointer now points to start of the network header
printf("\nType: %d\n", ntohs(eth_header->ether_type));
if(ntohs(eth_header->ether_type) == 0x0806)
{
printf("ARP detected \n");
// parseARP(payload);
}
else if(ntohs(eth_header->ether_type) == 0x0800)
{
printf("\nIP detected\n");
parseIP(payload);
}
}
【问题讨论】:
-
struct ip *ip_header = (struct ip*) *packet;好像很奇怪 -
怎么样?无论如何,程序不会在 seg 错误之前打印“before we cast ip header”,所以它必须在之前。 edit 刚刚记录了双 *.哎呀
-
我认为
struct ip *ip_header = (struct ip*) *packet;应该是struct ip *ip_header = (struct ip*) packet;...packet不是指针的指针!
标签: c network-programming segmentation-fault