[Techtalk] ip addreses on redhat

Almut Behrens almut-behrens at gmx.net
Tue Aug 5 00:06:14 EST 2003

On Mon, Aug 04, 2003 at 09:30:12AM -0700, Lena M wrote:
> thank you every one for pointing me in the right direction.
> I'll take a look at the source code a bit later today.

certainly, you'd figure it out yourself, sooner or later, but
maybe a minimal test/demo program could help to speed things up.

The C code below outputs the IP address of the "eth0" interface.
It roughly does it like ifconfig.
(btw, what programming language are you implementing your code in?)

What essentially needs to be done is to create a socket (INET) and
then do the appropriate ioctl() request on the socket handle -- here
SIOCGIFADDR (socket-IO-control-get-interface-address). This fills a
structure from which the IP address can be extracted:

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>

int main() {

    int sock;
    struct ifreq ifr;
    char *ip;
    int err = -1;

    strcpy(ifr.ifr_name, "eth0");
    ifr.ifr_addr.sa_family = AF_INET;

    sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (sock >= 0) {
        err = ioctl(sock, SIOCGIFADDR, &ifr);
        if (err == 0) {
            ip =  inet_ntoa(((struct sockaddr_in*) &(ifr.ifr_addr))->sin_addr);
            printf("IP-addr: %s\n", ip);
    return err;

(save this as get-ip.c, for example, and the compile it with
"gcc -o get-ip get-ip.c" -- sorry, if I'm telling you things you
already know; not sure how much programming experience you have...)

Also be sure to have a look a the relevant manpages and header files,
in particular if.h (for ifreq struct), ioctl.h (for SIOCGIFADDR),
socket.h (for sockaddr), etc. Usually, those header files include other
header files (e.g. bits/ioctls.h), which contain the actual definitions.
In case of doubt, simply do a recursive grep in /usr/include for the
string in question...


P.S.: as an alternative to investigating the source code of a program
to find out how it does something, it's often useful to do an 'strace'
on the program in action. This will give lots of information as to what
system calls are being made, what files are opened, searched for, etc. 
Just try it with "strace -o trace.out /sbin/ifconfig -a" -- the output
is reasonably compact...

P.P.S.: never use strcpy() in a real life production program, where the
source string, such as "eth0", can come from outside the program (user
input) -- I just used it here for brevity to not distract too much from
the more essential stuff. Always limit the length of what's being
copied, or else you'll have at least one potential buffer overflow

More information about the Techtalk mailing list