initial checkin
[grml-scripts-core.git] / compile / ip-screen.c
1 /*
2  * Filename:      ip-screen.c
3  * Purpose:       print ip address of configured network interfaces
4  * Authors:       grml-team (grml.org), (c) Michael Gebetsroither <gebi@grml.org>
5  * Bug-Reports:   see http://grml.org/bugs/
6  * License:       This file is licensed under the GPL v2.
7  * Latest change: Thu Mar 30 23:09:28 CEST 2006 [mika]
8  *********************************************************************************/
9
10 #include <unistd.h>
11 #include <string.h>
12 #include <stdlib.h>
13
14 #include <sys/types.h>
15 #include <sys/ioctl.h>
16 #include <sys/socket.h>
17 #include <net/if.h>
18 #include <netinet/in.h>
19 #include <arpa/inet.h>
20
21 #define MAX_IFS 32
22 #define WRITE(x) write(1, x, strlen(x))
23
24 // USER CONFIG
25 #define ERR_MSG "[running ip-screen failed]\n"
26 #define NO_IFACE_MSG "[ network n/a ]\n"
27
28 void die(int errcode)
29 {
30     WRITE(ERR_MSG);
31     exit(errcode);
32 }
33
34 int main()
35 {
36     int sockfd;
37     int total, remaining, current;
38     struct ifconf ifc;
39     struct ifreq *ifrp;
40     struct sockaddr_in *addr;
41     struct in_addr *tmp = NULL;
42     char buf[sizeof(struct ifreq)*MAX_IFS];
43     char *ctmp = NULL;
44
45     sockfd = socket(PF_INET,SOCK_DGRAM,0);
46     if(-1 == sockfd)
47         die(1);
48
49     ifc.ifc_buf = buf;
50     ifc.ifc_len = sizeof(buf);
51     if (-1 == ioctl(sockfd, SIOCGIFCONF, &ifc))
52         die(2);
53
54     remaining = total = ifc.ifc_len;
55     ifrp = ifc.ifc_req;
56     while(remaining) {
57         if( ifrp->ifr_addr.sa_family == AF_INET ) {
58             if (-1 == ioctl(sockfd, SIOCGIFFLAGS, ifrp)) {
59                 die(3);
60             }
61             addr = (struct sockaddr_in *)&(ifrp->ifr_addr);
62             if(!(ifrp->ifr_flags & IFF_LOOPBACK)) {
63                 if(tmp) {
64                     ctmp = inet_ntoa(*tmp);
65                     WRITE(ctmp);
66                     WRITE(" | ");
67                 }
68                 tmp = &addr->sin_addr;
69             }
70         }
71
72         current = sizeof(struct ifreq);
73         ifrp = (struct ifreq *)( ((char *)ifrp)+current );
74         remaining -= current;
75     }
76
77     if(tmp){
78         ctmp = inet_ntoa(*tmp);
79         WRITE(ctmp);
80         WRITE("\n");
81     } else {
82         WRITE(NO_IFACE_MSG);
83     }
84
85     return 0;
86 }
87
88 /** END OF FILE *****************************************************************/