view rtp-mgr/alloc.c @ 179:b79d6334f543

themwi-rtp-mgr: RTP port allocation split out of themwi-mgw
author Mychaela Falconia <falcon@freecalypso.org>
date Sat, 11 Mar 2023 20:19:14 -0800
parents mgw/crcx.c@f062c32a5116
children
line wrap: on
line source

/*
 * In this module we implement our RTP port allocation operation.
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <syslog.h>
#include <unistd.h>
#include "../include/tmgw_const.h"
#include "struct.h"
#include "select.h"

get_rtp_port_pair(roe, brc)
	struct rtp_one_end *roe;
	struct bind_range_cfg *brc;
{
	struct sockaddr_in sin;
	unsigned tries, rtp_port;
	int rc;

	sin.sin_family = AF_INET;
	sin.sin_addr = brc->bind_ip;
	for (tries = brc->port_tries; tries; tries--) {
		rtp_port = brc->port_next;
		brc->port_next += 2;
		if (brc->port_next >= brc->port_range_end)
			brc->port_next = brc->port_range_start;
		sin.sin_port = htons(rtp_port);
		roe->rtp_fd = socket(AF_INET, SOCK_DGRAM, 0);
		if (roe->rtp_fd < 0) {
			syslog(LOG_CRIT, "socket(AF_INET, SOCK_DGRAM, 0): %m");
			return(-1);
		}
		rc = bind(roe->rtp_fd, (struct sockaddr *) &sin, sizeof sin);
		if (rc < 0) {
			close(roe->rtp_fd);
			continue;
		}
		bcopy(&sin, &roe->bound_addr, sizeof(struct sockaddr_in));
		sin.sin_port = htons(rtp_port+1);
		roe->rtcp_fd = socket(AF_INET, SOCK_DGRAM, 0);
		if (roe->rtcp_fd < 0) {
			syslog(LOG_CRIT, "socket(AF_INET, SOCK_DGRAM, 0): %m");
			close(roe->rtp_fd);
			return(-1);
		}
		rc = bind(roe->rtcp_fd, (struct sockaddr *) &sin, sizeof sin);
		if (rc < 0) {
			close(roe->rtp_fd);
			close(roe->rtcp_fd);
			continue;
		}
		/* all good! */
		return(0);
	}
	/* couldn't find a free port pair */
	return(-1);
}