0

I'm beginner in Python and I would like to build simple port sniffer. For this purpose I'm using code from this site, as example: Simple packege snffer using python And I would like to unpack bites from socket to exctract http header, using function struct.unpack()

What format of string should I use in unpack HTTP header, (e.g '!BBH', "!BBHHHBBH4s4s",'!HHLLBBHHH')

1 Answer 1

3

the HTTP header is not fixed-length, so you'll need to parse it other way, for example:

import logging
log = logging.getLogger(__name__)


def parse_http(data):
        lines = data.split(b'\r\n')
        if len(lines) < 1:
            log.error('Invalid http header: %s', lines)
            return
        request = lines[0]
        header = {}
        rest = []
        in_header = True

        for line in lines[1:]:
            if line == b'':
                in_header = False
                continue
            if in_header:
                try:
                    key, val = line.split(b': ')
                except ValueError:
                    log.error('Invalid header line: %s', line)
                    continue
                header[key] = val
            else:
                rest.append(line)

        return request, header, b'\r\n'.join(rest)

In order to detect a HTTP packet, you could check if the payload starts with POST, GET, HTTP ... etc

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.