Const and pointers in C

The syntax of constant pointers in C can be confusing. Try reading from right to left, away from the variable name. E.g.

Pointer to a constant of type char:

const char *ptr_name;

Constant pointer to a variable of type char:

char *const ptr_name;

Constant pointer, to a constant of type char:

const char *const ptr_name;

Receiving raw packets in Linux without pcap

Since there was a lot of interest in my post on sending raw Ethernet packets, this is an example of receiving packets on a raw socket. A compiling version can be found on github: The application that I developed this for was to receive packets sent to a specific MAC address. The main sections are explained below:

Open raw socket listening for ETHER_TYPE

	if ((sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETHER_TYPE))) == -1) {
		perror("listener: socket");	
		return -1;

Set interface to promiscuous mode

	strncpy(ifopts.ifr_name, ifName, IFNAMSIZ-1);
	ioctl(sockfd, SIOCGIFFLAGS, &ifopts);
	ifopts.ifr_flags |= IFF_PROMISC;
	ioctl(sockfd, SIOCSIFFLAGS, &ifopts);

Allow socket to be reused

	if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof sockopt) == -1) {

Bind to device

	if (setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, ifName, IFNAMSIZ-1) == -1)	{

Receive on socket

	numbytes = recvfrom(sockfd, buf, BUF_SIZ, 0, NULL, NULL);
	printf("listener: got packet %lu bytes\n", numbytes);

Print the data

	for (i=0; i<numbytes; i++) printf("%02x:", buf[i]);

Close socket


My Git Cheat Sheet

I’ve been slowly adding to a cheat sheet I printed out a year ago. Half the commands I don’t use and the ones I use the most aren’t on there, so here’s mine…

Check out a new repo
git clone git://location/proj.git

Actually see what’s going on
gitk --all

Interactive adding for commits
git add -i

Unstage changes
git reset HEAD

Return to last committed state
git reset --hard

Undo a merge
git reset --hard [ID]
git reset --hard HEAD~[number back]

Undo a commit with message
git reset --soft HEAD^

Modify a commit
git commit --amend

Add more files to existing commit
git add ...
git commit --amend -C HEAD

Branches have diverged – just get up stream
git reset --hard @{upstream}

Checkout specific version of a file
git checkout [ID] [FILE]

Updating submodules
git submodule init
git submodule sync
git submodule update

Go through every submodule and checkout the head
git submodule foreach git checkout master
git submodule foreach git pull origin master
Or automatically merge
git submodule update --merge

Show difference between two branches
git diff [BRANCH 1]..[BRANCH 2]

Difference between two commits
git diff [ID1] [ID2]

Merge a branch back into master
git checkout master
git merge [BRANCH]

Show all branches
git branch --all

Checkout and track remote branch
git checkout -t [BRANCH]