Release new version 2.1.1
[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  *********************************************************************************/
8
9 #include <unistd.h>
10 #include <string.h>
11 #include <stdlib.h>
12
13 #include <sys/types.h>
14 #include <sys/ioctl.h>
15 #include <sys/socket.h>
16 #include <net/if.h>
17 #include <netinet/in.h>
18 #include <arpa/inet.h>
19
20 #define MAX_IFS 32
21 #define WRITE(x) write(1, x, strlen(x))
22
23 // USER CONFIG
24 #define ERR_MSG "[running ip-screen failed]\n"
25 #define NO_IFACE_MSG "[ network n/a ]\n"
26
27 void die(int errcode)
28 {
29     WRITE(ERR_MSG);
30     exit(errcode);
31 }
32
33 int main()
34 {
35     int sockfd;
36     int total, remaining, current;
37     struct ifconf ifc;
38     struct ifreq *ifrp;
39     struct sockaddr_in *addr;
40     struct in_addr *tmp = NULL;
41     char buf[sizeof(struct ifreq)*MAX_IFS];
42     char *ctmp = NULL;
43
44     sockfd = socket(PF_INET,SOCK_DGRAM,0);
45     if(-1 == sockfd)
46         die(1);
47
48     ifc.ifc_buf = buf;
49     ifc.ifc_len = sizeof(buf);
50     if (-1 == ioctl(sockfd, SIOCGIFCONF, &ifc))
51         die(2);
52
53     remaining = total = ifc.ifc_len;
54     ifrp = ifc.ifc_req;
55     while(remaining) {
56         if( ifrp->ifr_addr.sa_family == AF_INET ) {
57             if (-1 == ioctl(sockfd, SIOCGIFFLAGS, ifrp)) {
58                 die(3);
59             }
60             addr = (struct sockaddr_in *)&(ifrp->ifr_addr);
61             if(!(ifrp->ifr_flags & IFF_LOOPBACK)) {
62                 if(tmp) {
63                     ctmp = inet_ntoa(*tmp);
64                     WRITE(ctmp);
65                     WRITE(" | ");
66                 }
67                 tmp = &addr->sin_addr;
68             }
69         }
70
71         current = sizeof(struct ifreq);
72         ifrp = (struct ifreq *)( ((char *)ifrp)+current );
73         remaining -= current;
74     }
75
76     if(tmp){
77         ctmp = inet_ntoa(*tmp);
78         WRITE(ctmp);
79         WRITE("\n");
80     } else {
81         WRITE(NO_IFACE_MSG);
82     }
83
84     return 0;
85 }
86
87 /** END OF FILE *****************************************************************/