From 77a83472135eef19d9953898d106e6a5ab015912 Mon Sep 17 00:00:00 2001 From: Benjamin Franzke Date: Tue, 12 Mar 2013 10:13:10 +0100 Subject: util: Set SO_BROADCAST for udp eonnect sockets by default So that we can use it for econfind, and do not have the repeat all the code. --- econfind.c | 37 +------------------------------------ util.c | 7 +++++++ 2 files changed, 8 insertions(+), 36 deletions(-) diff --git a/econfind.c b/econfind.c index ae31a26..88bbbd3 100644 --- a/econfind.c +++ b/econfind.c @@ -17,8 +17,6 @@ #include #include -#include -#include #include #include @@ -29,39 +27,6 @@ #include "econproto.h" #include "econpacket.h" -static int -connect_broadcast(const char *addr, int port) -{ - int fd, ret; - struct sockaddr_in s; - int broadcast_enable = 1; - - memset(&s, 0, sizeof s); - s.sin_family = AF_INET; - s.sin_port = htons(port); - s.sin_addr.s_addr = inet_addr(addr); - - fd = socket(AF_INET, SOCK_DGRAM, 0); - if (fd == -1) - return -1; - ret = setsockopt(fd, SOL_SOCKET, SO_BROADCAST, - &broadcast_enable, sizeof(broadcast_enable)); - if (ret < 0) { - fprintf(stderr, "Failed to setsockopt broadcast: %s\n", - strerror(errno)), - close(fd); - return -1; - } - - if (connect(fd, (struct sockaddr *) &s, sizeof s) < 0) { - fprintf(stderr, "Failed to connect: %s\n", strerror(errno)); - close(fd); - return -1; - } - - return fd; -} - int main(int argc, char *argv[]) { @@ -73,7 +38,7 @@ main(int argc, char *argv[]) if (argc < 2) exit(EXIT_FAILURE); - cfd = connect_broadcast(argv[1], ECON_PORTNUMBER); + cfd = connect_to_host(SOCK_DGRAM, argv[1], STR(ECON_PORTNUMBER)); if (cfd < 0) exit(EXIT_FAILURE); diff --git a/util.c b/util.c index 867a8e0..4df5080 100644 --- a/util.c +++ b/util.c @@ -199,6 +199,13 @@ connect_to_host(int socktype, const char *host, const char *port) fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (fd == -1) continue; + if (socktype == SOCK_DGRAM) { + int broadcast_enable = 1; + if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, + &broadcast_enable, sizeof(broadcast_enable)) < 0) + fprintf(stderr, "Failed to setsockopt broadcast: %s\n", + strerror(errno)); + } if (connect(fd, rp->ai_addr, rp->ai_addrlen) != -1) break; -- cgit