C Segmentation Error

Associate
Joined
14 Jun 2010
Posts
737
Evening,

I have been learning C these last few days and trying examples from a book I have, One such program is giving me trouble with segmentation errors. I have found the two lines that are causing it by using GDB and a bit of trial and error.

I have checked the source code distributed with the book and it also has the same segmentation error upon compilation.

Here is the function the issue is occurring in:

Code:
void decode_ip(const u_char *header_start) {
	const struct ip_hdr *ip_header;

	ip_header = (const struct ip_hdr *)header_start;
	printf("\t((  Layer 3 ::: IP Header  ))\n");
	printf("\t( Source: %s\t", inet_ntoa(ip_header->ip_src_addr)); // Problem
	printf("Dest: %s )\n", inet_ntoa(ip_header->ip_dest_addr)); // Problem
	printf("\t( Type: %u\t", (u_int) ip_header->ip_type);
	printf("ID: %hu\tLength: %hu )\n", ntohs(ip_header->ip_id), ntohs(ip_header->ip_len));
}

I have commented the two lines that cause the segmentation error- everything runs fine when they're commented out.

Any help would be great, I am quite new to C. :(
 
Thanks for the fast replies.

ip_hdr is just a custom implementation of the standard IP layer header struct. (In /usr/include/netinet/ip.h)

It is just for readability's sake and to get used to writing structs.

In the "Official" ip.h file, 32 bits are required for the Source address and 32 bits for the Destination address. In my struct, they are each defined as an integer as 4 x 8 bits matches the specification. I didn't think I would run into any memory errors.

Reckon it is worth scrapping the custom struct? I have two others in my program that are very similar and work fine.
 
Phew, just found the issue with a look at that header file, some GDB and your point about endianness

It appears that the source and destination address are stored in little endian format, but inet_ntoa is expecting to receive it in big endian. Maybe I should write a function to reverse the byte order or replace the use of inet_ntoa- as it is mentioned that is is deprecated?
 
Just a quick update, I decided to scrap the use of the functions as they were causing some issues. Instead, I have printed the values of memory at an offset from the start of the structure header_start. This means that I am offsetting the value by the amount of information in the IP header I don't need. I could get rid of the ip_header struct all together and just access it from header_start.

Thank you very much for your help, I am pleased this now works. :)
 
Back
Top Bottom