Skip to content

Commit

Permalink
FreeBSD change for htons()
Browse files Browse the repository at this point in the history
robertdavidgraham committed May 26, 2021
1 parent 5bd8939 commit 9820cda
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions src/out-tcp-services.c
Original file line number Diff line number Diff line change
@@ -9,6 +9,22 @@
#endif
#include <ctype.h>

/**
* This is a stupid hack to avoid dependencies. I want to minimize the dependence
* on network libraries. For example, I get a warning message on FreeBSD about
* a missing `htons()`. I could just add a system header, but then this increases
* dependencies on other things. Alternatively, I could just implement the
* function myself. So I chose that route.
*/
static unsigned short my_htons(unsigned port)
{
static const char test[2] = "\x11\x22";
if (*(unsigned short*)test == 0x1122)
return (unsigned short)(0xFFFF & port);
else
return (unsigned short)((port>>8)&0xFF) | ((port&0xFF)<<8);
}

#if _MSC_VER
#define strdup _strdup
#endif
@@ -30,7 +46,7 @@ tcp_service_name(int port)
struct servent *result;
char buf[2048];

r = getservbyport_r(htons(port), "tcp", &result_buf,buf, sizeof(buf), &result);
r = getservbyport_r(my_htons(port), "tcp", &result_buf,buf, sizeof(buf), &result);

/* ignore ERANGE - if the result can't fit in 2k, just return unknown */
if (r != 0 || result == NULL)
@@ -41,7 +57,7 @@ tcp_service_name(int port)
{
struct servent *result;

result = getservbyport(htons((unsigned short)port), "tcp");
result = getservbyport(my_htons((unsigned short)port), "tcp");

if (result == 0)
return "unknown";
@@ -62,7 +78,7 @@ udp_service_name(int port)
struct servent *result;
char buf[2048];

r = getservbyport_r(htons(port), "udp", &result_buf,buf, sizeof(buf), &result);
r = getservbyport_r(my_htons(port), "udp", &result_buf,buf, sizeof(buf), &result);

/* ignore ERANGE - if the result can't fit in 2k, just return unknown */
if (r != 0 || result == NULL)
@@ -73,7 +89,7 @@ udp_service_name(int port)
{
struct servent *result;

result = getservbyport(htons((unsigned short)port), "udp");
result = getservbyport(my_htons((unsigned short)port), "udp");

if (result == 0)
return "unknown";

0 comments on commit 9820cda

Please sign in to comment.