straight-shoota
9/12/2018 - 11:03 AM

Test support of SO_REUSEPORT

Test support of SO_REUSEPORT

// Simple program to test support of SO_REUSEPORT
// Adapted from https://blog.dubbelboer.com/2016/04/23/so-reuseport.html

#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <unistd.h>

int main() {
#ifdef SO_REUSEPORT
  int sock = socket(AF_INET, SOCK_STREAM, 0);
  int reuse = 1;
  int size = sizeof(reuse);
  if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void*)&reuse, size) < 0) {
    if (errno == EINVAL || errno == ENOPROTOOPT) {
      printf("SO_REUSEPORT is not supported by your kernel\n");
    } else {
      printf("unknown error\n");
    }
  } else {
    printf("SO_REUSEPORT is supported\n");
    if (getsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void*)&reuse, &size) < 0) {
      if(errno == ENOPROTOOPT) {
        printf("failed getsockopt: protocol not supported\n");
      } else {
        printf("unknown error\n");
      }
    } else {
      printf("getsockopt works: %d", reuse);
    }
  }
  close(sock);
#else
  printf("SO_REUSEPORT is not supported by your include files\n");
#endif
  return 0;
}
SO_REUSEPORT is supported
failed getsockopt: protocol not supported