| 1 | = Obtaining Interface Information = |
| 2 | |
| 3 | |
| 4 | This is based on an answer posted to the RTEMS User's mailing list by [wiki:ThomasRauscher ThomasRauscher] http://www.rtems.com/ml/rtems-users/2004/november/msg00255.html. |
| 5 | |
| 6 | |
| 7 | '''Question:''' What is the best way to obtain my IP address, MAC Address, Network Mask, and Default Gateway after the |
| 8 | ''rtems''bsdnet''initialize''network()_ call? I want to be able to access this information from software. |
| 9 | |
| 10 | |
| 11 | '''Answer:''' This should do the trick. 'ifname' should contain the name of your interface, e.g. "eth0", 'addr' then contains the result. |
| 12 | |
| 13 | |
| 14 | {{{ |
| 15 | #include <sys/types.h> |
| 16 | #include <sys/ioctl.h> |
| 17 | #include <sys/socket.h> |
| 18 | #include <net/if.h> |
| 19 | #include <netinet/in.h> |
| 20 | |
| 21 | int get_ifaddr(const char *ifname, struct in_addr *addr) |
| 22 | { |
| 23 | int fd; |
| 24 | int rc; |
| 25 | struct ifreq ifreq; |
| 26 | struct sockaddr_in *sockaddr; |
| 27 | |
| 28 | fd = socket(AF_INET, SOCK_DGRAM, 0); |
| 29 | if(fd<0) { |
| 30 | return -1; |
| 31 | } |
| 32 | |
| 33 | strcpy(ifreq.ifr_name, ifname); |
| 34 | |
| 35 | rc = ioctl(fd, SIOCGIFADDR, &ifreq); |
| 36 | if(rc == 0) |
| 37 | { |
| 38 | sockaddr = (struct sockaddr_in *) &ifreq.ifr_ifru.ifru_addr; |
| 39 | memcpy(addr, &sockaddr->sin_addr, sizeof(*addr)); |
| 40 | } |
| 41 | |
| 42 | close(fd); |
| 43 | return (rc==0) ? 0 : -1; |
| 44 | } |
| 45 | }}} |