evelina
evelina

Reputation: 157

How to test from userspace if the kernel supports IPv6?

I am seeking for a simple way to test if the kernel supports IPv6 on Linux in C/C++. Is it enough to check if the socket() call fails and that errno is set to EINVAL ?

Upvotes: 0

Views: 1283

Answers (2)

user2610053
user2610053

Reputation: 526

Yes, it's safe to use socket(7), e.g.

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

int is_ipv6_enabled(void) {
  int ret = 0;

#ifdef AF_INET6
  int fd = socket(AF_INET6, SOCK_STREAM, 0);
  if (fd == -1) {
    ret = errno != EAFNOSUPPORT;
  } else {
    ret = 1;
    close(fd);
  }
#endif /* AF_INET6 */

  return ret;
}

Upvotes: 1

Indeed, read ipv6(7): the call to socket(7)-s routines, notably socket(2) and others, e.g. bind(2) etc..., could fail (and you should always handle such failures anyway).

You could also use proc(5) e.g. read /proc/net/if_inet6 or /proc/net/sockstat6 (I believe it won't exist if ipv6 is unsupported).

Upvotes: 3

Related Questions