NATMap: Reuse the same port unless it is unavailable (#126)

Fixes #120
This commit is contained in:
发飙的公牛
2026-02-14 08:52:45 +08:00
committed by GitHub
parent c131eeb55f
commit 4905dbf4d4
4 changed files with 20 additions and 13 deletions

View File

@@ -245,21 +245,23 @@ hev_conf_baddr (void)
}
const char *
hev_conf_bport (void)
hev_conf_bport (int next)
{
static char port[16];
if (brand) {
int n = bport[1] - bport[0] + 1;
bport[2] = bport[0] + (rand () % n);
}
if (!port[0] || next) {
if (brand) {
int n = bport[1] - bport[0] + 1;
bport[2] = bport[0] + (rand () % n);
}
snprintf (port, sizeof (port) - 1, "%u", bport[2]);
snprintf (port, sizeof (port) - 1, "%u", bport[2]);
if (!brand) {
bport[2] = bport[2] + 1;
if (bport[2] > bport[1]) {
bport[2] = bport[0];
if (!brand) {
bport[2] = bport[2] + 1;
if (bport[2] > bport[1]) {
bport[2] = bport[0];
}
}
}

View File

@@ -113,12 +113,13 @@ const char *hev_conf_baddr (void);
/**
* hev_conf_bport:
* @next: switch to the next port
*
* Get bind port for port mapping.
*
* Returns: returns string.
*/
const char *hev_conf_bport (void);
const char *hev_conf_bport (int next);
/**
* hev_conf_taddr:

View File

@@ -26,6 +26,7 @@
static struct sockaddr_storage saddr;
static HevTask *task;
static int port_next;
static int timeout;
static int fd;
@@ -98,13 +99,14 @@ tnsk_run (void)
http = hev_conf_http ();
tfwd = hev_conf_taddr ();
addr = hev_conf_baddr ();
port = hev_conf_bport ();
port = hev_conf_bport (port_next);
hport = hev_conf_hport ();
iface = hev_conf_iface ();
mark = hev_conf_mark ();
fd = hev_sock_client_base (type, SOCK_STREAM, addr, port, http, hport,
iface, mark, &saddr, NULL);
port_next = (fd < 0);
if (fd < 0) {
LOGV (E, "%s", "Start TCP keep-alive service failed.");
return;

View File

@@ -27,6 +27,7 @@
static struct sockaddr_storage saddr;
static struct sockaddr_storage daddr;
static HevTask *task;
static int port_next;
static int timeout;
static unsigned int cycle;
@@ -95,7 +96,7 @@ unsk_run (void)
type = hev_conf_type ();
ufwd = hev_conf_taddr ();
addr = hev_conf_baddr ();
port = hev_conf_bport ();
port = hev_conf_bport (port_next);
stun = hev_conf_stun ();
sport = hev_conf_sport ();
iface = hev_conf_iface ();
@@ -105,6 +106,7 @@ unsk_run (void)
fd = hev_sock_client_base (type, SOCK_DGRAM, addr, port, stun, sport, iface,
mark, &saddr, &daddr);
port_next = (fd < 0);
if (fd < 0) {
LOGV (E, "%s", "Start UDP keep-alive service failed.");
return;