C - get home dir location in linux

20. February 2012 08:00

 

This is a short example of how to get the home directory location in linux in a C program. There is really a few choices here and depending on what your requirements are you might want to use one or other methods. The first method can be changed by the user. The second method cannot. However if the first method fails you should drop faill back on the other method.

 

The simple method is to pull the enviroment variable "HOME"

 

The slightly more complex method is to read it from the system user database.

 

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>


int main(int argc, char **argv) {


        char *homedir = getenv("HOME");

        if (homedir != NULL) {
                printf("Home dir in enviroment");
                printf("%s\n", homedir);
        }

        uid_t uid = getuid();
        struct passwd *pw = getpwuid(uid);

        if (pw == NULL) {
                printf("Failed\n");
                exit(EXIT_FAILURE);
        }

        printf("%s\n", pw->pw_dir);

        return 0;
}

 

E-mail Kick it! DZone it! del.icio.us Permalink


C - ip address validation

17. February 2012 08:00

 

A short example to show how to check and ip address is actually an ip address in C. I have seen a number of time that people provide solution using reg'ex and various other methods to attempt to do this. However there is a standard function that will test for you.

 

The function is called inet_pton will be able to tell you if a string is acutally an ip address or not. Typically the function also has another use which is to convert an ip address into its network byte ordered integer format.

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <arpa/inet.h>

int main(int argc, char **argv) {
    unsigned long ip = 0;

    if (argc < 2) {
        printf("Usage: %s <ipv4>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if (0 == inet_pton(AF_INET, argv[1], &ip)) {
        printf("Failed\n");
        exit(EXIT_FAILURE);
    }

    printf("IP: %ld\n", ip);
    return 0;
}

E-mail Kick it! DZone it! del.icio.us Permalink


C - Get current ip address of an interface

15. February 2012 08:00

 

This is a short example to retrive an ip address from an interface in linux. It is typically used to be able to bind a port to a specific address on a machine.

 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <net/if.h>

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

int main(int argc, char **argv) {
    int sock = socket(PF_INET, SOCK_DGRAM, 0);
    struct ifreq req;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <interfacename>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if (sock < 0) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    memset(&req, 0, sizeof(req));
    strncpy(req.ifr_name, argv[1], IF_NAMESIZE - 1);

    if (ioctl(sock, SIOCGIFADDR, &req) < 0) {
        perror("ioctl");
        exit(EXIT_FAILURE);
    }

    printf("%s\n", inet_ntoa(((struct sockaddr_in *)&req.ifr_addr)->sin_addr));


    close(sock);

    exit(EXIT_SUCCESS);
    return 0;
}

 

E-mail Kick it! DZone it! del.icio.us Permalink


Read / Write a pid for a file in linux

13. February 2012 08:00

 

This is a short example to show you how to read and write a process id to a file in linux.

 

First the write.

 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argc, char **argv) {
    pid_t pid = getpid();

    if (argc < 2) {
        printf("Usage: %s <filename>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    FILE *fp = fopen(argv[1], "w");
    if (!fp) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    fprintf(fp, "%d\n", pid);

    fclose(fp);

    return EXIT_SUCCESS;
}

 

 

Then the read

 

 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argc, char **argv) {
    pid_t pid = 0;

    if (argc < 2) {
        printf("Usage: %s <filename>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    FILE *fp = fopen(argv[1], "r");
    if (!fp) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    if (fscanf(fp, "%d\n", &pid) == 1) {
        printf("PID: %d\n", pid);
    } else {
        printf("Failed to Read PID\n");
    }

    fclose(fp);

    return EXIT_SUCCESS;
}

 

E-mail Kick it! DZone it! del.icio.us Permalink


Using asprintf instead of sprintf or snprintf

10. February 2012 08:00

 

One of the problem that has always existed in c programming is to create a big enough buffer in order to store a string. This can create a chicken / egg problem when trying to use sprintf or snprintf where you don't know how big the buffer actually needs to be to store the string.

 

There is another function in linux which will allocate a buffer which is called asprintf (allocate string printf). this will make sure that the buffer is always going to be big enough to store the data and does not suffer from the same problems when using sprintf or snprintf.

 

The cost of using this is of course is performance releated since it needs to allocate memory and you also need to free it later. This type of allocation can be expensive if called a large number of times. There is also of course the problem of remembering to free the allocated memory later or it will create a memory leak.

 

To use this function you also need to define _GNU_SOURCE on the gcc command line (of in the program with a define before the includes)

 

Here is an example of using asprintf.

 

 

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    char *tmp = 0;

    if (asprintf(&tmp, "%s %d", "Magic Number", 1234) < 0) {
        perror("asprintf");
        exit(EXIT_FAILURE);
    }

    printf("%s\n", tmp);

    free(tmp);

    return 0;
}

 

E-mail Kick it! DZone it! del.icio.us Permalink