python和C语言混合编程实例


Posted in Python onJune 04, 2014

最近为了测试网速情况怎么样,由于部分业务服务器需要关闭icmp,这样的话采用普通的ping就无法适应我的需求,于是自己简单的写了一个基于tcp端口的ping的程序,由于c执行效率比较的不错,但是开发效率低下,而python是开发效率高,但是执行效率不如C,由于需要大规模的使用,于是用C实现核心部分的代码,并把这部分实现成一个python的模块,由python调用c的模块,下面就贴代码吧

/* tcpportping.c */
#include <Python.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/time.h>/* count time functions */
static double mytime(void)
{
    struct timeval tv;
    if (gettimeofday(&tv, NULL) == -1)
        return 0.0;
    return (double)tv.tv_usec + (double)tv.tv_sec * 1000000;
}
static PyObject *                                 /* returns object */
tcpping(PyObject *self, PyObject *args )
{
    struct  sockaddr_in addr;
    struct  hostent *hp;
    double  time;
    char    *host = NULL;
    int     fd;
    int     port, timeout;
    if (!PyArg_ParseTuple(args, "sii", &host, &port, &timeout))  /* convert Python -> C */
        return NULL;                              /* null=raise exception */
    if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        return Py_BuildValue("d", -1.0);        /* convert C -> Python */
    }
    bzero((char *)&addr, sizeof(addr));
    if ((hp = gethostbyname(host)) == NULL) {
        return Py_BuildValue("d", -2.0);        /* convert C -> Python */
    }
    bcopy(hp->h_addr, &addr.sin_addr, hp->h_length);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    struct timeval tv;
    tv.tv_sec = 0;
    tv.tv_usec = timeout * 1000;
    double stime = mytime();
    if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        return Py_BuildValue("d", -3.0);        /* convert C -> Python */
    }
    fd_set read, write;
    FD_ZERO(&read);
    FD_ZERO(&write);
    FD_SET(fd, &read);
    FD_SET(fd, &write);
    if (select(fd + 1, &read, &write, NULL, &tv) == 0) {
        close(fd);
        return Py_BuildValue("d", -4.0);        /* convert C -> Python */
    }
    double etime = mytime();
    time = etime - stime;
    if (!FD_ISSET(fd, &read) && !FD_ISSET(fd, &write)) {
        close(fd);
        return Py_BuildValue("d", -4.0);        /* convert C -> Python */
    }
    close(fd);
    return Py_BuildValue("d", time/1000);        /* convert C -> Python */
}
/* registration table  */
static struct PyMethodDef portping_methods[] = {
    {"tcpping", tcpping, METH_VARARGS},       /* method name, C func ptr, always-tuple */
    {NULL, NULL}                   /* end of table marker */
};
/* module initializer */
void inittcpportping( )                       /* called on first import */
{                                      /* name matters if loaded dynamically */
    (void) Py_InitModule("tcpportping", portping_methods);   /* mod name, table ptr */
}

编译成python模块

gcc tcpportping.c  -I/usr/include/python2.4 -shared -L/usr/bin -fpic -lpython2.4 -o tcpportping.so

下面是python调用c模块的代码:

#!/usr/bin/env pythonimport tcpportping
import time
i = 0
while i < 5:
    t = tcpportping.tcpping('www.baidu.com', 80, 1000)
    if t < 0:
        print "time out"
    else:
        print t
    time.sleep(0.5)
    i += 1

执行python代码就可以实现端口ping的结果,从测试的情况来看,该程序执行的结果跟普通的ping几乎没有什么差别。
Python 相关文章推荐
使用python解析xml成对应的html示例分享
Apr 02 Python
python使用分治法实现求解最大值的方法
May 12 Python
Python 的描述符 descriptor详解
Feb 27 Python
使用Python对Access读写操作
Mar 30 Python
Numpy数组的保存与读取方法
Apr 04 Python
在cmd中查看python的安装路径方法
Jul 03 Python
Python识别快递条形码及Tesseract-OCR使用详解
Jul 15 Python
python几种常用功能实现代码实例
Dec 25 Python
python+selenium+PhantomJS抓取网页动态加载内容
Feb 25 Python
python实现手势识别的示例(入门)
Apr 15 Python
Python3读写ini配置文件的示例
Nov 06 Python
教你用python实现一个无界面的小型图书管理系统
May 21 Python
python实现的一个p2p文件传输实例
Jun 04 #Python
python实现文件分组复制到不同目录的例子
Jun 04 #Python
python实现的udp协议Server和Client代码实例
Jun 04 #Python
Python实现同时兼容老版和新版Socket协议的一个简单WebSocket服务器
Jun 04 #Python
Python程序员鲜为人知但你应该知道的17个问题
Jun 04 #Python
Python和Ruby中each循环引用变量问题(一个隐秘BUG?)
Jun 04 #Python
python控制台英汉汉英电子词典
Apr 23 #Python
You might like
成本8450万,票房仅2亿,口碑两极分化,又一部DC电影扑街了
2020/04/09 欧美动漫
php生成mysql的数据字典
2016/07/07 PHP
php断点续传之文件分割合并详解
2016/12/13 PHP
ThinkPHP3.2.3框架Memcache缓存使用方法实例总结
2019/04/15 PHP
Thinkphp 框架扩展之驱动扩展实例分析
2020/04/27 PHP
在Javascript中为String对象添加trim,ltrim,rtrim方法
2006/09/22 Javascript
使用JS进行目录上传(相当于批量上传)
2010/12/05 Javascript
jQuery中filter()和find()的区别深入了解
2013/09/25 Javascript
Javascript基础教程之while语句
2015/01/18 Javascript
JS实现左右拖动改变内容显示区域大小的方法
2015/10/13 Javascript
JS简单获取当前日期时间的方法(如:2017-03-29 11:41:10 星期四)
2017/03/29 Javascript
解决jQuery ajax动态新增节点无法触发点击事件的问题
2017/05/24 jQuery
Angularjs渲染的 using 指令的星级评分系统示例
2017/11/09 Javascript
jquery无缝图片轮播组件封装
2020/11/25 jQuery
解决layui 三级联动下拉框更新时回显的问题
2019/09/03 Javascript
vue中上传视频或图片或图片和文字一起到后端的解决方法
2019/12/01 Javascript
Python语言的12个基础知识点小结
2014/07/10 Python
Python内建数据结构详解
2016/02/03 Python
python生成器表达式和列表解析
2016/03/10 Python
Django rest framework基本介绍与代码示例
2018/01/26 Python
python文件操作之批量修改文件后缀名的方法
2018/08/10 Python
详解Python匿名函数(lambda函数)
2019/04/19 Python
Python 依赖库太多了该如何管理
2019/11/08 Python
Ranorex通过Python将报告发送到邮箱的方法
2020/01/12 Python
pandas中的ExcelWriter和ExcelFile的实现方法
2020/04/24 Python
python使用自定义钉钉机器人的示例代码
2020/06/24 Python
python如何利用Mitmproxy抓包
2020/10/10 Python
Python在后台自动解压各种压缩文件的实现方法
2020/11/10 Python
澳大利亚鞋仓库:Shoe Warehouse
2019/07/25 全球购物
仓库班组长岗位职责
2013/12/12 职场文书
幼儿教师国培感言
2014/02/19 职场文书
大学活动总结格式
2014/04/29 职场文书
2014年妇委会工作总结
2014/12/10 职场文书
干部个人考察材料
2014/12/24 职场文书
阳光体育运动标语口号
2015/12/26 职场文书
python实现局部图像放大
2021/11/17 Python