现在的位置: 首页 > 综合 > 正文

备用代码,For Linux

2013年03月19日 ⁄ 综合 ⁄ 共 1119字 ⁄ 字号 评论关闭
   这里写的一些代码,是最近工作中的总结.  不成片段,不能单独编译,但是在以后编程中可能会用到, 所以记录于此.
  
1.使用boost库创建线程.
   以下创建两个线程,boost库允许给指定线程函数传入参数,可以用boost::bind()函数来指定线程函数的参数.
  

void Fun1();
void Fun2(string str_val);

string str_1;

boost::thread thrd1(
&Fun1);
boost::thread thrd2(boost::bind(
&Fun2,str_1));
thrd1.join();
thrd2.join();

2.抓取某个网络接口的数据包,使用libpcap.

buf_u_int32 mask,net;
struct pcap_pkthdr header;
const char* packet;
pcap_t
* handle=NULL;
struct bpf_program fp;

void got_packet(u_char* args,const pcap_pkthdr* header,
const u_char* packet)
{
//..
}


if(pcap_lookupnet("eth0",&net,&mask,errbuf)!=-1)
{
   handle 
= pcap_open_live("eth0",BUFSIZ,1,1000,errbuf);
   
if(handle)
   
{
      
if(pcap_compile(handle,&fp,"ip",0,net)!=-1)
         
if(pcap_setfilter(handle,&fp)!=-1)
         
{
            pcap_loop(handle,
0,got_packet,NULL);
         }

   }

}

3.获得当前日期和时间值

size_t GetLocalTime(char* time_format)
{
   time_t time_ts;
   
struct tm* local_time_tm;
   sizt_t time_size;
   
   
if((time_ts = time(&time_ts))!=-1)
   
{
       local_time_tm 
= localtime(&time_ts);
       
if((time_size=strftime(time_format,MAX_TIME_LEN,"%F %X %z",local_time_tm))!=0)
         
return time_size;
   }

   
return 0;
}

抱歉!评论已关闭.