]> git.neil.brown.name Git - metad.git/blob - broadcast.c
Assorted reformating
[metad.git] / broadcast.c
1
2 /* broadcast a string on all interfaces, to udp_port(); */
3
4 #include        <sys/types.h>
5 #include        <unistd.h>
6 #include        <sys/socket.h>
7 #include        <sys/ioctl.h>
8 #ifdef SOLARIS
9 #include        <sys/sockio.h>
10 #endif
11 #include        <netinet/in.h>
12 #include        <net/if.h>
13 #include        <fcntl.h>
14 #include        <netdb.h>
15 #include        <stdio.h>
16 #include        <memory.h>
17
18 int udp_port(void);
19
20 static struct ifconf    iflist;
21 static int interfaces;
22 static int sock;
23
24 static int ifconfinit()
25 {
26
27         static char buf[2048];
28
29         iflist.ifc_len = sizeof(buf);
30         iflist.ifc_buf = buf;
31 /*      printf("ifc_len = %d\n", iflist.ifc_len);       / **/
32         if (ioctl(sock, SIOCGIFCONF, (char *)&iflist)< 0) return -1;
33 /*      printf("ifc_len = %d\n", iflist.ifc_len);       / **/
34         interfaces = iflist.ifc_len / sizeof(struct ifreq);
35 #if 0
36 /*      printf("interfaces = %d\n",interfaces);         / **/
37 /*      for (in=0; in<interfaces ; in++) if (iflist.ifc_req[in].ifr_name[0]=='\0') break; */
38 /*      interfaces = in; */
39 /*      printf("interfaces = %d\n",interfaces);         / **/
40 #endif
41         return 0;
42 }
43
44 static void sendaddr(struct sockaddr_in addr, char *packet)
45 {
46         addr.sin_port = udp_port();
47         addr.sin_family = AF_INET;
48
49         sendto(sock, packet, strlen(packet), 0, (struct sockaddr *)&addr, sizeof(addr));
50 }
51
52 static void sendinter(int n, char *packet)
53 {
54         struct ifreq ifr;
55
56         ifr = iflist.ifc_req[n];
57 /*    printf("interface = %s\n", ifr.ifr_name); */
58         ioctl(sock, SIOCGIFBRDADDR, &ifr);
59         sendaddr(*(struct sockaddr_in*)&ifr.ifr_broadaddr, packet);
60 }
61
62 void broadcast(char *packet)
63 {
64
65         int n;
66         int port;
67         struct sockaddr_in      myaddr;
68         int a = -1;
69
70
71         sock = socket(AF_INET, SOCK_DGRAM, 0);
72         setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char*)&a, 4);
73         memset(&myaddr, 0, sizeof(myaddr));
74         myaddr.sin_family = AF_INET;
75         if (geteuid()==0)
76                 port = 1023;
77         else
78                 port = 10230;
79         myaddr.sin_port = htons(port);
80         while (bind(sock, (struct sockaddr *)&myaddr, sizeof(myaddr))== -1) myaddr.sin_port = htons(--port);
81         if (ifconfinit()!= -1)          /* gets list of interfaces */
82                 for (n = 0 ; n < interfaces ; n++)
83                         sendinter(n, packet);
84 }