Date: Sat, 13 Oct 2001 19:09:09 +0100 From: David Taylor <davidt@yadt.co.uk> To: Paolo Pisati <flag@libero.it> Cc: freebsd-hackers@FreeBSD.ORG Subject: Re: First prg with sysctl Message-ID: <20011013190909.A29541@gattaca.yadt.co.uk> In-Reply-To: <20011013194902.A38183@newluxor.skynet.org>; from flag@libero.it on Sat, Oct 13, 2001 at 19:49:02 %2B0200 References: <20011013194902.A38183@newluxor.skynet.org>
index | next in thread | previous in thread | raw e-mail
On Sat, 13 Oct 2001, Paolo Pisati wrote:
>
> Someone can tell me why this piece of code doesn't work?
>
> #include<stdio.h>
> #include <sys/types.h>
> #include <sys/socket.h>
> #include <sys/sysctl.h>
> #include <sys/time.h>
> #include <net/if.h>
> #include <net/if_mib.h>
>
> int main(void) {
> int mib[5], *count;
Here you define 'count' as an uninitialised pointer to an integer.
> mib[0]=CTL_NET;
> mib[1]=PF_LINK;
> mib[2]=NETLINK_GENERIC;
> mib[3]=IFMIB_SYSTEM;
> mib[4]=IFMIB_IFCOUNT;
>
> sysctl(mib, 5, count, sizeof(int),(void *)NULL, NULL);
Here, in arg three, you pass the value of 'count' as the address to store
the count in, so you're storing it in some random address, probably
resulting in -1 being returned with errno=EFAULT.
In arg 4, you pass 'sizeof(int)' (probably 4) as the address of a size_t
containing the length of the value, also probably resulting in EFAULT.
In arg 5, casting NULL to (void *) is somewhat redundant.
In arg 6, you probably want to use 0, since the arg isn't a pointer.
You also don't check the return value for success/failure.
> printf("count: %d\n",*count);
You then dereference the random piece of memory.
Consider something like:
+++ sysctl.c Sat Oct 13 19:08:44 2001
@@ -1,3 +1,4 @@
+#include <errno.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
@@ -7,7 +8,9 @@
#include <net/if_mib.h>
int main(void) {
- int mib[5], *count;
+ int mib[5];
+ int count;
+ int len;
mib[0]=CTL_NET;
mib[1]=PF_LINK;
@@ -15,8 +18,12 @@
mib[3]=IFMIB_SYSTEM;
mib[4]=IFMIB_IFCOUNT;
- sysctl(mib, 5, count, sizeof(int),(void *)NULL, NULL);
-
- printf("count: %d\n",*count);
+ len = sizeof(int);
+ if (sysctl(mib, 5, &count, &len, NULL, 0) == -1)
+ {
+ perror("sysctl");
+ exit(1);
+ }
+ printf("count: %d\n",count);
}
--
David Taylor
davidt@yadt.co.uk
To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message
help
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20011013190909.A29541>
