wiki:TBR/UserManual/Obtaining_Interface_Information
Notice: We have migrated to GitLab launching 2024-05-01 see here: https://gitlab.rtems.org/

Version 1 (modified by Vdcappel, on 04/04/08 at 14:06:35) (diff)

Conversion from e-mail introduced some spurious 's in the code

Obtaining Interface Information

This is based on an answer posted to the RTEMS User's mailing list by ThomasRauscher? http://www.rtems.com/ml/rtems-users/2004/november/msg00255.html.

Question: What is the best way to obtain my IP address, MAC Address, Network Mask, and Default Gateway after the rtemsbsdnetinitializenetwork()_ call? I want to be able to access this information from software.

Answer: This should do the trick. 'ifname' should contain the name of your interface, e.g. "eth0", 'addr' then contains the result.

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

int get_ifaddr(const char *ifname, struct in_addr *addr)
{
    int fd;
    int rc;
    struct ifreq ifreq;
    struct sockaddr_in *sockaddr;

    fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(fd<0) {
        return -1;
    }

    strcpy(ifreq.ifr_name, ifname);

    rc = ioctl(fd, SIOCGIFADDR, &ifreq);
    if(rc == 0)
    {
        sockaddr = (struct sockaddr_in *) &ifreq.ifr_ifru.ifru_addr;
        memcpy(addr, &sockaddr->sin_addr, sizeof(*addr));
    }

    close(fd);
    return (rc==0) ? 0 : -1;
}