Python uses C extensions to send packets.

prepare C files to be compiled using C extensions

-sharpinclude <stdio.h>
-sharpinclude <stdlib.h>
-sharpinclude <unistd.h>
-sharpinclude <string.h>
-sharpinclude <errno.h>
-sharpinclude <netdb.h>
-sharpinclude <netinet/in.h>
-sharpinclude <netinet/ip.h>
-sharpinclude <netinet/tcp.h>
-sharpinclude <netinet/if_ether.h>
-sharpinclude <arpa/inet.h>
-sharpinclude <sys/socket.h>
-sharpinclude <pcap.h>
-sharpinclude <Python.h>

static PyObject *
demo_send(PyObject *self, PyObject *args)
{
    const char* packet;
    const int length;
    // convert PyObject to C values
    if (!PyArg_ParseTuple(args, "si", &packet, &length))
        return NULL;

    char *dev; 
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t* descr;
    dev = pcap_lookupdev(errbuf);
    if(dev == NULL) {
        fprintf(stderr,"%s\n",errbuf); 
        exit(1);
    }

    descr = pcap_open_live(dev,BUFSIZ,1,-1,errbuf);
    if(descr == NULL) { 
        printf("pcap_open_live(): %s\n",errbuf); 
        exit(1); 
    }   
    int sts = pcap_sendpacket(descr, packet, length); 
    return Py_BuildValue("i", sts);;
}
// module"s method table
static PyMethodDef DemoMethods[] = {
    {"send", demo_send, METH_VARARGS, "Send packets"},
    {NULL, NULL, 0, NULL} 
};

// module" s initialization function
PyMODINIT_FUNC
initdemo(void)
{
    (void)Py_InitModule("Csend", DemoMethods);
}

and setup.py files

from distutils.core import setup, Extension

module1 = Extension("Csend",
                sources = ["release.c"]
                )

setup (name = "a demo extension module",
   version = "1.0",
   description = "send packets",
   ext_modules = [module1])

but the compiled result has the error of
"ImportError:. / Csend.so: undefined symbol: pcap_sendpacket"
.

clipboard.png

gcc-lpcap

clipboard.png

I want to use C to speed up the delivery of python projects. As a result, there is a problem with using C extension during compilation. If there are any other options for sending packages, you can also ask for advice. Thank you!

Jun.22,2022

< H2 > areas to be corrected < / H2 >
  • PyMODINIT_FUNC function name must be init < module name > . Suppose the module name is csend , then

    PyMODINIT_FUNC
    initcsend(void)
    {
        (void)Py_InitModule("csend", DemoMethods);
    }

    this module name must be the same as in setup.py .

  • The external dependent library of the

    c module should be written to setup.py , such as

     module1 = Extension(
         'csend',
         sources=['release.c'],
         include_dirs=['/usr/include'],
         libraries=['pcap'],  -sharp 
         library_dirs=['/usr/lib'],
     )
  • use python setup.py install to install the module, or package it and send it somewhere else to install.
    package as source

    python setup.py sdist

    or binary package

    python setup.py bdist_wininst
    python setup.py bdist_rpm
    python setup.py bdist_dumb
< H2 > other delivery methods < / H2 >
Menu