2

The code in question comes from here (so you can see the full context) : https://www.anmolsarma.in/post/dccp/

Within the calls below to setsockopt, there are two pieces I can't seem to find information on, mostly because I don't know what to google because I don't know what its called.

&(int) {1},

And :

&(int) {htonl(SERVICE_CODE)}

So, what do the {} do in this context? I can totally see doing it with normal parenthesis, but I thought {} were reserved for other uses.

eg:

&(int)(htonl(SERVICE_CODE))

Does that have the same meaning as above? I've never seen something like that inserted into a function call before. I'm not sure if its C or C++, I suspect just C (based on the includes). I'm wondering if it is somehow related to htonl sometimes being a macro and sometimes being a function and how trying to use it within the parameter list on a function might cause problems? What is this construct called (so I can google and do more research)?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>

#include "dccp.h"

#define PORT 1337
#define SERVICE_CODE 42

int error_exit(const char *str)
{
    perror(str);
    exit(errno);
}

int main(int argc, char **argv)
{
    int listen_sock = socket(AF_INET, SOCK_DCCP, IPPROTO_DCCP);
    if (listen_sock < 0)
        error_exit("socket");

    struct sockaddr_in servaddr = {
        .sin_family = AF_INET,
        .sin_addr.s_addr = htonl(INADDR_ANY),
        .sin_port = htons(PORT),
    };

    if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &(int) {
               1}, sizeof(int)))
        error_exit("setsockopt(SO_REUSEADDR)");

    if (bind(listen_sock, (struct sockaddr *)&servaddr, sizeof(servaddr)))
        error_exit("bind");

    // DCCP mandates the use of a 'Service Code' in addition the port
    if (setsockopt(listen_sock, SOL_DCCP, DCCP_SOCKOPT_SERVICE, &(int) {
               htonl(SERVICE_CODE)}, sizeof(int)))
        error_exit("setsockopt(DCCP_SOCKOPT_SERVICE)");

...
}
LawfulEvil
  • 2,267
  • 24
  • 46

0 Answers0