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
[EMAIL PROTECTED]

To Unsubscribe: send mail to [EMAIL PROTECTED]
with "unsubscribe freebsd-hackers" in the body of the message

Reply via email to