Here is the function I am trying to get to working on Red Hat 6..
And I have very little experience with C, and especially using #define, so I’m unsure what this portion is even trying to do: SP->s_port = htons(SP->s_port);
#ifdef __linux
#define GET_SERVICE_BY_NAME(SP, SERVICE, PROTOCOL) \
char GSBN_servbuf[HOSTBUFFERLENGTH] = {0}; \
struct servent GSBN_sp; \
struct servent *GSBN_serv_result; \
int GSBN_s = 0; \
GSBN_s = getservbyname_r(SERVICE, \
PROTOCOL, \
&GSBN_sp, \
GSBN_servbuf, \
sizeof(GSBN_servbuf), \
&GSBN_serv_result); \
SP = GSBN_serv_result; \
SP->s_port = htons(SP->s_port); \
if (SP && SOCKET_DEBUG) { \
printf("%s GET_SERVICE_BY_NAME - Service: %s Port: %d Protocol: %s\n", \
get_timestamp(), SP->s_name, SP->s_port, SP->s_proto); \
} \
if (SP == NULL) { \
fprintf(stderr, "%s GET_SERVICE_BY_NAME - Service %s not found.\n", \
get_timestamp(), SERVICE); \
}
#else
#define GET_SERVICE_BY_NAME(SP, SERVICE, PROTOCOL) \
char GSBN_servbuf[HOSTBUFFERLENGTH] = {0}; \
struct servent GSBN_serv_result; \
SP = getservbyname_r(SERVICE, \
PROTOCOL, \
&GSBN_serv_result, \
GSBN_servbuf, \
sizeof(GSBN_servbuf)); \
if (SP && SOCKET_DEBUG) { \
printf("%s GET_SERVICE_BY_NAME - Service: %s Port: %d Protocol: %s\n", \
get_timestamp(), SP->s_name, SP->s_port, SP->s_proto); \
} \
if (SP == NULL) { \
fprintf(stderr, "%s GET_SERVICE_BY_NAME - Service %s not found.\n", \
get_timestamp(), SERVICE); \
}
#endif
This is the error I am getting:
According to gdb I am getting a seg fault at this function call:
GET_SERVICE_BY_NAME(sp, serv, prot);
Here is the gdb output:
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x456c6c90 (LWP 14645)]
0x420b1e69 in gi_get_port (serv=Unhandled dwarf expression opcode 0x9c
)
at /home/user1/Common/src/socket.c:282
282 GET_SERVICE_BY_NAME(sp, serv, prot);
Current language: auto; currently c
Here is how the function is called:
int gi_get_port (char *serv, char *prot)
/* obtain the port for the named service */
{
int p, s;
/* Data for resolving service name to a socket description. */
struct servent *sp = NULL;
GET_SERVICE_BY_NAME(sp, serv, prot);
if (sp != NULL) {
p = sp->s_port;
} else {
p = -1;
};
return p;
}
This is what your code will look like once the preprocessor is executed :
As you see, you should be checking for ‘sp’ being ‘NULL’ before you do the htons() on the port.