Skip to content

Commit

Permalink
receiver: network: add error checking
Browse files Browse the repository at this point in the history
Add error checking to make network failures visible, such as
trying to binding to a port that is already in-use by another
process.
  • Loading branch information
pawitp authored and duncanthrax committed May 1, 2024
1 parent c8de372 commit 402ebf0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
20 changes: 16 additions & 4 deletions Receivers/unix/network.c
Original file line number Diff line number Diff line change
@@ -1,23 +1,35 @@
#include "network.h"
#include "stdio.h"

static rctx_network_t rctx_network;

int init_network(enum receiver_type receiver_mode, in_addr_t interface, int port, char* multicast_group)
{
rctx_network.sockfd = socket(AF_INET,SOCK_DGRAM,0);
rctx_network.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (rctx_network.sockfd < 0) {
perror("Failed to craete socket");
return 1;
}

memset((void *)&(rctx_network.servaddr), 0, sizeof(rctx_network.servaddr));
rctx_network.servaddr.sin_family = AF_INET;
rctx_network.servaddr.sin_addr.s_addr = (receiver_mode == Unicast) ? interface : htonl(INADDR_ANY);
rctx_network.servaddr.sin_port = htons(port);
bind(rctx_network.sockfd, (struct sockaddr *)&rctx_network.servaddr, sizeof(rctx_network.servaddr));

if (bind(rctx_network.sockfd, (struct sockaddr *)&rctx_network.servaddr, sizeof(rctx_network.servaddr)) != 0) {
perror("Failed to bind to interface");
return 1;
}

if (receiver_mode == Multicast) {
rctx_network.imreq.imr_multiaddr.s_addr = inet_addr(multicast_group ? multicast_group : DEFAULT_MULTICAST_GROUP);
rctx_network.imreq.imr_interface.s_addr = interface;

setsockopt(rctx_network.sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(const void *)&rctx_network.imreq, sizeof(struct ip_mreq));
if (setsockopt(rctx_network.sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(const void *)&rctx_network.imreq, sizeof(struct ip_mreq)) != 0) {
perror("Failed to join multicast group");
return 1;
};
}

return 0;
Expand Down
4 changes: 3 additions & 1 deletion Receivers/unix/scream.c
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,9 @@ int main(int argc, char*argv[]) {
case Multicast:
default:
if (verbosity) fprintf(stderr, "Starting %s receiver\n", receiver_mode == Unicast ? "unicast" : "multicast");
init_network(receiver_mode, interface, port, multicast_group);
if (init_network(receiver_mode, interface, port, multicast_group) != 0) {
return 1;
}
receiver_rcv_fn = rcv_network;
break;
}
Expand Down

0 comments on commit 402ebf0

Please sign in to comment.