2

Where do I set TCP_NODELAY in this C++ TCP Client?

    // Client socket descriptor which is just integer number used to access a socket
    int sock_descriptor;
    struct sockaddr_in serv_addr;

    // Structure from netdb.h file used for determining host name from local host's ip address
    struct hostent *server;

    // Create socket of domain - Internet (IP) address, type - Stream based (TCP) and protocol unspecified
    // since it is only useful when underlying stack allows more than one protocol and we are choosing one.
    // 0 means choose the default protocol.
    sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);

    if (sock_descriptor < 0)
        printf("Failed creating socket\n");

    bzero((char *) &serv_addr, sizeof(serv_addr));

    server = gethostbyname(host);

    if (server == NULL) {
        printf("Failed finding server name\n");
        return -1;
    }

    serv_addr.sin_family = AF_INET;

    memcpy((char *) &(serv_addr.sin_addr.s_addr), (char *) (server->h_addr), server->h_length);

    // 16 bit port number on which server listens
    // The function htons (host to network short) ensures that an integer is
    // interpreted correctly (whether little endian or big endian) even if client and
    // server have different architectures
    serv_addr.sin_port = htons(port);

    if (connect(sock_descriptor, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
        printf("Failed to connect to server\n");
        return -1;
    } else
        printf("Connected successfully - Please enter string\n");
3
  • Call setsocketopt any time after you get the socket descriptor. Due diligence requires me to ask why you want to turn Nagel off. Nagel is your friend. Aug 13, 2015 at 20:22
  • @user4581301 Because comms are from a vm to its host.
    – BAR
    Aug 13, 2015 at 20:39
  • Still going to have to eat all of the extra packet overhead. If you are aiming for low latency, may I recommend UDP, possibly with a lightweight handshake to confirm receipt, instead? Aug 13, 2015 at 21:01

1 Answer 1

3

TCP_NODELAY is option given to setsockopt system call:

#include <netinet/tcp.h>

int yes = 1;
int result = setsockopt(sock,
                        IPPROTO_TCP,
                        TCP_NODELAY,
                        (char *) &yes, 
                        sizeof(int));    // 1 - on, 0 - off
 if (result < 0)
      // handle the error

This is to set Nagle buffering off. You should turn this option on only if you really know what you are doing.

2
  • TCP_NODELAY is not found. What library should I be importing?
    – BAR
    Aug 13, 2015 at 20:41
  • 4
    got it. #include <netinet/tcp.h>
    – BAR
    Aug 13, 2015 at 20:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.