view utils/sip-udp-dump.c @ 43:5995660dcbac

sip-rx-test, sip-udp-dump: fix bind error handling
author Mychaela Falconia <falcon@freecalypso.org>
date Sun, 04 Sep 2022 21:38:02 -0800
parents 87c077b23996
children
line wrap: on
line source

/*
 * This debug utility binds to UDP port 5060 (SIP) and dumps any/all
 * packets received at this port.  A one-line summary is printed to
 * stdout, and the full SIP INVITE packet content is written to a file.
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>

static int sock;
static FILE *logf;
static char dgram[4096];
static unsigned dgram_len;
static struct sockaddr_in sin;
static time_t curtime;

static void
log_full_packet()
{
	fprintf(logf, "From %s:%u %u bytes %s", inet_ntoa(sin.sin_addr),
		ntohs(sin.sin_port), dgram_len, ctime(&curtime));
	fwrite(dgram, 1, dgram_len, logf);
	putc('\n', logf);
	fflush(logf);
}

static void
print_header_line()
{
	char *cp;

	cp = index(dgram, '\n');
	if (cp)
		*cp = '\0';
	puts(dgram);
}

main(argc, argv)
	char **argv;
{
	int rc;
	socklen_t addrlen;

	if (argc != 2) {
		fprintf(stderr, "usage: %s logfile\n", argv[0]);
		exit(1);
	}
	logf = fopen(argv[1], "a");
	if (!logf) {
		perror(argv[1]);
		exit(1);
	}
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock < 0) {
		perror("socket");
		exit(1);
	}
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;
	sin.sin_port = htons(5060);
	rc = bind(sock, (struct sockaddr *) &sin, sizeof sin);
	if (rc < 0) {
		perror("bind");
		exit(1);
	}
	for (;;) {
		addrlen = sizeof sin;
		rc = recvfrom(sock, dgram, sizeof(dgram) - 1, 0,
				(struct sockaddr *) &sin, &addrlen);
		if (rc < 0) {
			perror("recvfrom");
			exit(1);
		}
		time(&curtime);
		dgram_len = rc;
		dgram[dgram_len] = '\0';
		log_full_packet();
		print_header_line();
	}
}