Saturday, November 2, 2013

Python Networking: Socket Options

I love writing code in python. Well, who doesn't. Network programming has always been an interesting topic to code about and Python has great support for it.
Whether you are trying to learn the concepts and design patterns of net programming or building a production service which requires any level of network programming, Python is a great choice.

However, dealing with sockets at lower levels could give you a little bit of headache.A specific problem which I've come across time to time is how to access socket options.

Socket options are, ..., options, to control (or monitor) different aspects of underlying mechanisms for sending and receiving data.

Options are organized into levels like IP level or TCP level. You can find a list of TCP level options here.
For example if you need to know about the status of your connection, something like what netstat command prints, you have to get the tcp_info option from TCP level. let's do that:

  1. 1) you need to know the type (and size) of the value you are going to receive.In this case it can be looked up here. It's "__u8"*7 + "__u32"*24 = 104
  2. you are going to use python's struct module to parse the returned value.
  3. use socket.getsockopt method to access the options with the correct level and option name.
  4. in the parsed value, you need the right item (First in this case).

The overall operation would be something like this:

    def getTCPInfo(s):
        fmt = "B"*7+"I"*21
        x = struct.unpack(fmt, s.getsockopt(socket.IPPROTO_TCP, socket.TCP_INFO, 104))
        print x

I've posted a complete version of this here, previously.
Remember that each option of each level might require different approach but the general steps is the same.


No comments:

Post a Comment