Access to sysctl on FreeBSD?

S

Skye

How do I access the sysctl(3) call from Python on BSD?

Specifically I want to retrieve:

$ sysctl -d net.inet.ip.stats
net.inet.ip.stats: IP statistics (struct ipstat, netinet/ip_var.h)

So I'll need some way of getting to struct ipstat from Python as well

Thanks,
Skye
 
M

Martin v. Löwis

How do I access the sysctl(3) call from Python on BSD?
Specifically I want to retrieve:

$ sysctl -d net.inet.ip.stats
net.inet.ip.stats: IP statistics (struct ipstat, netinet/ip_var.h)

So I'll need some way of getting to struct ipstat from Python as well

At the moment, only through ctypes - if you need to use sysctl(3),
and you'll have to manufacture the layout of struct ipstat yourself.

Regards,
Martin
 
S

Skye

Great, thanks for the help (I'm fairly new to Python, didn't know
about ctypes)

from ctypes import *
libc = CDLL("libc.so.7")
size = c_uint(0)
libc.sysctlbyname("net.inet.ip.stats", None, byref(size), None, 0)
buf = c_char_p(" " * size.value)
libc.sysctlbyname("net.inet.ip.stats", buf, byref(size), None, 0)

So now that I've got the data, can you point me towards docs
explaining how to layout struct ipstat?

Thanks,
Skye
 
S

Skye

Nevermind, I seem to have found it on my own =]

http://python.org/doc/2.5/lib/module-struct.html

This module performs conversions between Python values and C structs
represented as Python strings. It uses format strings (explained
below) as compact descriptions of the lay-out of the C structs and the
intended conversion to/from Python values. This can be used in
handling binary data stored in files or from network connections,
among other sources.

I freakin' love Python!!

Skye
 
T

Thomas Heller

Skye said:
Great, thanks for the help (I'm fairly new to Python, didn't know
about ctypes)

from ctypes import *
libc = CDLL("libc.so.7")
size = c_uint(0)
libc.sysctlbyname("net.inet.ip.stats", None, byref(size), None, 0)
buf = c_char_p(" " * size.value)
libc.sysctlbyname("net.inet.ip.stats", buf, byref(size), None, 0)

IIUC, sysctlbyname writes the information you requested into the buffer supplied
as second argument. If this is true, then the above code is incorrect.
c_char_p(src) creates an object that shares the buffer with the Python string 'src';
but Python strings are immutable and you must not write ctypes code that modifies them.

Instead, you should code:

from ctypes import *
libc = CDLL("libc.so.7")
size = c_uint(0)
libc.sysctlbyname("net.inet.ip.stats", None, byref(size), None, 0)
buf = create_string_buffer(size.value)
libc.sysctlbyname("net.inet.ip.stats", buf, byref(size), None, 0)

Thomas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top