There is very little error checking in this, and I have not filtered out the loopback interface.
compiles as is, but required libsocket and libnsl
cc -lsocket -lnsl -o ifprint ifprint.c
[highlight=c]
/*
ifprint.c - prints active network interfaces
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/dlpi.h>
#include <net/if.h>
#include <sys/sockio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#define SOCKET_AF(af) (((af) == AF_UNSPEC) ? AF_INET : (af))
int main(int argc, char *argv[])
{
struct lifreq lifr
int64_t onflags = 0;
int64_t offflags = 0;
int setaddr;
int n;
int af = AF_INET;
char *buf;
int s = socket(SOCKET_AF(af), SOCK_DGRAM, 0);
struct lifnum lifn;
struct lifconf lifc;
struct lifreq lifrp;
struct lifreq lifrl; / Local lifreq struct */
int numifs;
unsigned bufsize;
int plumball = 0;
int save_af = af;
int64_t lifc_flags = LIFC_NOXMIT | LIFC_TEMPORARY | LIFC_ALLZONES;
lifn.lifn_family = AF_UNSPEC;
lifn.lifn_flags = lifc_flags;
if \(ioctl\(s, SIOCGLIFNUM, \(char *\)&lifn\) < 0\) \{
/* Could not determine number of interfaces */
exit\(2\);
\}
numifs = lifn.lifn_count;
bufsize = numifs * sizeof \(struct lifreq\);
if \(\(buf = malloc\(bufsize\)\) == NULL\) \{
/* out of memory */
\(void\) close\(s\);
exit\(1\);
\}
lifc.lifc_family = AF_UNSPEC;
lifc.lifc_flags = lifc_flags;
lifc.lifc_len = bufsize;
lifc.lifc_buf = buf;
if \(ioctl\(s, SIOCGLIFCONF, \(char *\)&lifc\) < 0\) \{
free\(buf\);
exit\(1\);
\}
lifrp = lifc.lifc_req;
for \(n = lifc.lifc_len / sizeof \(struct lifreq\); n > 0; n--, lifrp\+\+\) \{
\(void\) close\(s\);
af = lifrp->lifr\_addr.ss_family;
s = socket\(SOCKET_AF\(af\), SOCK_DGRAM, 0\);
if \(s == -1\) \{
exit\(1\);
\}
if \(onflags || offflags\) \{
\(void\) memset\(&lifrl, 0, sizeof \(lifrl\)\);
\(void\) strncpy\(lifrl.lifr_name, lifrp->lifr_name,
sizeof \(lifrl.lifr_name\)\);
if \(ioctl\(s, SIOCGLIFFLAGS, \(caddr_t\)&lifrl\) < 0\) \{
\(void\) strncpy\(lifr.lifr_name,
lifrp->lifr_name, sizeof \(lifr.lifr_name\)\);
printf\("foreachinterface: SIOCGLIFFLAGS\\n"\);
exit\(1\);
\}
if \(\(lifrl.lifr_flags & onflags\) != onflags\)
continue;
if \(\(~lifrl.lifr_flags & offflags\) != offflags\)
continue;
\}
\(void\) strncpy\(lifrl.lifr_name, lifrp->lifr_name,
sizeof \(lifrl.lifr_name\)\);
if \(ioctl\(s, SIOCGLIFADDR, \(caddr_t\)&lifrl\) < 0\) \{
\(void\) strncpy\(lifr.lifr_name,
lifrp->lifr_name, sizeof \(lifr.lifr_name\)\);
printf\("foreachinterface: SIOCGLIFADDR\\n"\);
continue;
\}
if \(lifrl.lifr\_addr.ss_family != af\) \{
af = lifrl.lifr\_addr.ss_family;
\(void\) close\(s\);
s = socket\(SOCKET_AF\(af\), SOCK_DGRAM, 0\);
if \(s == -1\) \{
\(void\) strncpy\(lifr.lifr_name,
lifrp->lifr_name,
sizeof \(lifr.lifr_name\)\);
printf\("socket\\n"\);
exit\(1\);
\}
\}
setaddr = 0;
/* print the name of the interface */
printf\("%s\\n", lifrp->lifr_name\);
\}
if \(buf != NULL\)
free\(buf\);
}
[/highlight]