Linux Programming FAQs




Copyright © 2008-2009 by Zack Smith
All rights reserved.

This is just a collection of Linux-specific programming tips that I've collected over time.

How do I get the terminal size?

#include <sys/ioctl.h>
struct winsize sz;
if (ioctl (0, TIOCGWINSZ, (char*) &sz))
    perror("ioctl");
else
    printf ("rows=%d, cols=%d\n", sz.ws_row, sz.ws_col);

How do I detect that the terminal size has changed?

int routine(int signal)
{
    if (signal==SIGWINCH)
        printf ("Terminal size has changed.\n");
}

main() 
{
    signal(SIGWINCH, &routine);
    ...
}

How do I get the ethernet or wireless MAC address?

#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>

void
getmac (char *name, unsigned char *addr)
{
    struct ifreq buf;
    int s = socket (PF_INET, SOCK_DGRAM, 0);
    int i;
    bzero (&buf, sizeof(struct ifreq));
    strcpy (buf.ifr_name, name);
    ioctl (s, SIOCGIFHWADDR, &buf);
    close (s);
    for (i=0; i<6; i++)
        addr[i] = buf.ifr_hwaddr.sa_data[i];
}

Links