sock: Use sysctl helpers to access /proc/sys/ params
[netsniff-ng.git] / sysctl.c
blob283d4031a60743249e92a7be0a35e6bb60196e82
1 /*
2 * sysctl - sysctl set/get helpers
3 * Subject to the GPL, version 2.
4 */
6 #include <stdio.h>
7 #include <fcntl.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <linux/limits.h>
13 #include "built_in.h"
15 #define SYS_PATH "/proc/sys/"
17 int sysctl_set_int(const char *file, int value)
19 char path[PATH_MAX];
20 char str[64];
21 ssize_t ret;
22 int fd;
24 strncpy(path, SYS_PATH, PATH_MAX);
25 strncat(path, file, PATH_MAX - sizeof(SYS_PATH) - 1);
27 fd = open(path, O_WRONLY);
28 if (unlikely(fd < 0))
29 return -1;
31 ret = snprintf(str, 63, "%d", value);
32 if (ret < 0) {
33 close(fd);
34 return -1;
37 ret = write(fd, str, strlen(str));
39 close(fd);
40 return ret <= 0 ? -1 : 0;
43 int sysctl_get_int(const char *file, int *value)
45 char path[PATH_MAX];
46 char str[64];
47 ssize_t ret;
48 int fd;
50 strncpy(path, SYS_PATH, PATH_MAX);
51 strncat(path, file, PATH_MAX - sizeof(SYS_PATH) - 1);
53 fd = open(path, O_RDONLY);
54 if (fd < 0)
55 return -1;
57 ret = read(fd, str, sizeof(str));
58 if (ret > 0) {
59 *value = atoi(str);
60 ret = 0;
61 } else {
62 ret = -1;
65 close(fd);
66 return ret;