Capturing beacon frames in 802.11 - wifi

How can I capture 802.11 beacon frames on my linux machine using a C program.Also how can I send a frame response using a C program?

Try using libpcap. See this answer on SO for a basic example.

below program only work :-
1. if your device support link layer type as DLT_IEEE802_11_RADIO
2. if you ahev libpacp installed in your machine.
3. compile it with libcap library( ex:- cc prog.c -lpcap
4. during run provide interface on command line ( ex:- a.out wlan0)
#include <pcap.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void packet_view(unsigned char *args,const struct pcap_pkthdr *h,const unsigned char *p);
#define SNAP_LEN 3000
void packet_view(
unsigned char *args,
const struct pcap_pkthdr *h,
const unsigned char *p
){
int len;
len = 0;
printf("PACKET\n");
while(len < h->len) {
printf("%02x ", *(p++));
if(!(++len % 16))
printf("\n");
}
printf("\n");
return ;
}
int main(int argc, char **argv)
{
char *dev = NULL; /* capture device name */
char errbuf[PCAP_ERRBUF_SIZE]; /* error buffer */
pcap_t *handle; /* packet capture handle */
char filter_exp[] = "wlan type mgt subtype beacon"; /* filter expression [3] */
// char filter_exp[] = "ip"; /* filter expression [3] */
struct bpf_program fp; /* compiled filter program (expression) */
bpf_u_int32 mask; /* subnet mask */
bpf_u_int32 net; /* ip */
int num_packets = 10; /* number of packets to capture */
/* check for capture device name on command-line */
if (argc == 2) {
dev = argv[1];
}
else if (argc > 2) {
fprintf(stderr, "error: unrecognized command-line options\n\n");
exit(EXIT_FAILURE);
}
else {
/* find a capture device if not specified on command-line */
dev = pcap_lookupdev(errbuf);
if (dev == NULL) {
fprintf(stderr, "Couldn't find default device: %s\n",
errbuf);
exit(EXIT_FAILURE);
}
}
/* get network number and mask associated with capture device */
if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
fprintf(stderr, "Couldn't get netmask for device %s: %s\n",
dev, errbuf);
net = 0;
mask = 0;
}
/* print capture info */
printf("Device: %s\n", dev);
printf("Number of packets: %d\n", num_packets);
printf("Filter expression: %s\n", filter_exp);
/* open capture device */
handle = pcap_open_live(dev, SNAP_LEN, 1, -1, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
exit(EXIT_FAILURE);
}
/* for Ethernet device change the type to DLT_EN10MB */
/* your wlan device need to supprot this link layer type otherwise failure */
if (pcap_datalink(handle) != DLT_IEEE802_11_RADIO) {
fprintf(stderr, "%s is not an Wlan packet\n", dev);
exit(EXIT_FAILURE);
}
/* compile the filter expression */
if (pcap_compile(handle, &fp, filter_exp, 1,PCAP_NETMASK_UNKNOWN) == -1) {
fprintf(stderr, "Couldn't parse filter %s: %s\n",
filter_exp, pcap_geterr(handle));
exit(EXIT_FAILURE);
}
/* apply the compiled filter */
if (pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n %s: %s\n",
filter_exp, pcap_geterr(handle));
exit(EXIT_FAILURE);
}
/* now we can set our callback function */
pcap_loop(handle, num_packets, packet_view, NULL);
/* cleanup */
pcap_freecode(&fp);
pcap_close(handle);
printf("\nCapture complete.\n");
return 0;
}

Related

Connecting stdout to stdin of the same process in Linux

I'm writing an app that (ab)uses an APL engine, libapl.so. The library contains a mechanism to allow me to capture results, but some stuff it dumps to stdout and stderr. So my question is, is there way a to capture stuff written to stdout rather than having it go to a screen, get piped to another process, or some such? Is there a way, for example, to connect stdout to stdin of the same process? I've tinkered with pipe2(), dup(2), and various bits of weirdness in GTK+/Glib, but I haven't hit the right incantation yet.
Did some more poking--at least one solution seems to be to create a fifo, open() it twice, once for reading, one for writing, and dup2() the writing fd to the stdout fd. This results in writes to stdout going through the fifo pipe where it can be read by the application. (Thanks for some inspiration by someone named Hasturkun, almost 7 years ago.)
Here's a bit of demo code:
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int
main (int ac, char *av[])
{
char tname[64];
sprintf (tname, "/tmp/testpipe%d", (int)getpid ());
int rc = mkfifo (tname, 0666);
if (rc != 0) {
perror ("Creating fifo");
return 1;
}
int temp_in_fd = open (tname, O_NONBLOCK | O_RDONLY);
if (temp_in_fd < 0) {
perror ("Opening new input");
return 1;
}
int temp_out_fd = open (tname, O_NONBLOCK | O_WRONLY);
if (temp_out_fd < 0) {
perror ("Opening new output");
return 1;
}
FILE *temp_in = fdopen (temp_in_fd, "r");
if (!temp_in) {
perror ("Creating new input FILE");
return 1;
}
FILE *temp_out = fdopen (temp_out_fd, "w");
if (!temp_out) {
perror ("Creating new input FILE");
return 1;
}
dup2 (fileno (temp_out), STDOUT_FILENO);
printf("Woot!");
fflush(stdout);
#define BFR_SIZE 64
char bfr[BFR_SIZE];
ssize_t sz = fread (bfr, 1, BFR_SIZE, temp_in);
fprintf (stderr, "got %d bytes: \"%s\"\n", (int)sz, bfr);
fclose (temp_out);
fclose (temp_in);
unlink (tname);
return 0;
}

Imlib2 file loading error

I have installed Imlib2 on my computer, however doing the example program as below (having changed the line for loading files to include the error code) I keep getting the error code 4.
/* standard headers */
#include <X11/Xlib.h>
#include <Imlib2.h>
#include <stdio.h>
#include <string.h>
/* main program */
int main(int argc, char **argv)
{
/* an image handle */
Imlib_Image image;
Imlib_Load_Error err;
/* if we provided < 2 arguments after the command - exit */
if (argc != 3) exit(1);
/* load the image */
image = imlib_load_image_with_error_return(argv[1],&err);
if(err) printf("load error:%d",err);
/* if the load was successful */
if (image)
{
char *tmp;
imlib_context_set_image(image);
tmp = strrchr(argv[2], '.');
if(tmp)
imlib_image_set_format(tmp + 1);
imlib_save_image(argv[2]);
}
}

gstreamer 1.0 sdk application to capture RTP Video Issue

I have ran this code many times trying to figure out why it doesn't work. I am getting the feed from a IP camera. The program goes through each but then it fails to play. The original start out was gst-launch-1.0 udpsrc address=[ip] port=[port] ! application/x-rtp,clock-rate=10,media=video ! rtpmp4vdepay ! decodebin ! d3dvideosink
I used gst_parse_launch() with it and works but for some reason won't play. I have been trying figure out what I am doing wrong.
convertString.h just throws the Char *port to a method to convert string to int.I don't want to use the gst_parse_launch() because I am wanting to use it to overlay into application.
Anybody have any idea what I am missing?
#include <gst/gst.h>
#include <gst/video/videooverlay.h>
#include <stdio.h>
#include <string.h>
#include "convertString.h"
#include <Windows.h>
#include <direct.h>
void nullvalues(GstElement*,GstBus*,GstMessage*);
int main(int argc, char *argv[])
{
GstElement *pipeline,*sink,*source, *rtppay,*filter1,*decodebin;
GstCaps *filtercaps;
GstBus *bus;
GstMessage *msg;
gboolean link_ok = FALSE;
GstStateChangeReturn ret;
char *ip_address = [ip];
char *port = [port];
char *window_handle = "";
char *title = "";
int wid;
char *sourcestring = "";
#define url_size 28
char url[url_size];
strcpy_s(url,url_size,"");
while ((argc > 1) && (argv[1][0] == '-'))
{
switch (argv[1][1])
{
case 'i':
ip_address = &argv[1][2];
break;
case 'p':
port = &argv[1][2];
break;
case 'w':
window_handle = &argv[1][2];
break;
case 't':
title = &argv[1][2];
break;
}
++argv;
--argc;
}
strcat_s(url,url_size,"udp://");
strcat_s(url,url_size,ip_address);
strcat_s(url,url_size,":");
strcat_s(url,url_size,port);
/* Initialize GStreamer */
gst_init(&argc,&argv);
/* Build Pipeline */
if(title != "")
pipeline = gst_pipeline_new (title);
else
pipeline = gst_pipeline_new("My pipeline");
source = gst_element_factory_make ("udpsrc","source");
filter1 = gst_element_factory_make("capsfilter","filter");
rtppay = gst_element_factory_make( "rtpmp4vdepay", "depayl");
decodebin = gst_element_factory_make ("decodebin","decode");
sink = gst_element_factory_make ("d3dvideosink", "sink");
gst_bin_add_many (GST_BIN (pipeline),source,filter1,rtppay,decodebin,sink, NULL);
filtercaps = gst_caps_new_simple("application/x-rtp","clock-rate",G_TYPE_INT,10,"media",G_TYPE_STRING,"video",NULL);
g_object_set(GST_OBJECT(source),"address",ip_address,NULL);
g_object_set(GST_OBJECT(source),"port",StringToInt(port),NULL);
g_object_set (G_OBJECT (filter1), "caps",filtercaps,NULL);
gst_caps_unref(filtercaps);
link_ok = gst_element_link_many(source,filter1,rtppay,decodebin,sink);
if(!link_ok)
printf("%s\nNOPE\n");
/* Start playing */
ret = gst_element_set_state (pipeline, GST_STATE_READY);
if(ret == GST_STATE_CHANGE_FAILURE)
printf("\nFailed\n");
else if(ret == GST_STATE_CHANGE_SUCCESS)
printf("\nSuccess\n");
/* Wait until error or EOS */
bus = gst_element_get_bus (pipeline);
msg = gst_bus_timed_pop_filtered(bus,GST_CLOCK_TIME_NONE,GST_MESSAGE_ERROR | GST_MESSAGE_EOS);
/* Free resources */
if (msg != NULL)
gst_message_unref (msg);
gst_object_unref (bus);
gst_element_set_state (pipeline, GST_STATE_NULL);
gst_object_unref (pipeline);
printf("\nDone\n");
return 0;
}
If gst_parse_launch() is working for you I suggest to use it. You can still overlay the d3dvideosink in your application.
Just use a unique name for the d3dvideosink element in the pipeline definition (e.g. "d3dvideosink name=myvideosink").
Get a handle to the d3dvideosink from the pipeline via gst_bin_get_by_name(). This handle should then also support the GstVideoOverlay interface and you can set the overlay via gst_video_overlay_set_window_handle().
using this will solve the problem
Gstreamer Decodebin

objectmaker.exe in haarclassification

I am trying in vs2012 and opencv 2.4.11 to run the objectmaker.exe in my project file which is created by the code and successfully build in release but when i am trying to double click to open it there is a run time error i cant fix it any help please .. my code is :
#include <opencv/cv.h>
#include <opencv/cvaux.h>
#include <opencv/highgui.h>
#include "stdafx.h"
#include "opencv2/highgui/highgui.hpp"
// for filelisting
#include <stdio.h>
#include <io.h>
// for fileoutput
#include <string>
#include <fstream>
#include <sstream>
#include "dirent.h"
#include <sys/types.h>
using namespace std;
using namespace cv;
IplImage* image=0;
IplImage* image2=0;
//int start_roi=0;
int roi_x0=0;
int roi_y0=0;
int roi_x1=0;
int roi_y1=0;
int numOfRec=0;
int startDraw = 0;
char* window_name="<SPACE>add <ENTER>save and load next <ESC>exit";
string IntToString(int num)
{
ostringstream myStream; //creates an ostringstream object
myStream << num << flush;
/*
* outputs the number into the string stream and then flushes
* the buffer (makes sure the output is put into the stream)
*/
return(myStream.str()); //returns the string form of the stringstream object
};
void on_mouse(int event,int x,int y,int flag, void *param)
{
if(event==CV_EVENT_LBUTTONDOWN)
{
if(!startDraw)
{
roi_x0=x;
roi_y0=y;
startDraw = 1;
} else {
roi_x1=x;
roi_y1=y;
startDraw = 0;
}
}
if(event==CV_EVENT_MOUSEMOVE && startDraw)
{
//redraw ROI selection
image2=cvCloneImage(image);
cvRectangle(image2,cvPoint(roi_x0,roi_y0),cvPoint(x,y),
CV_RGB(255,0,255),1);
cvShowImage(window_name,image2);
cvReleaseImage(&image2);
}
}
int main(int argc, char** argv)
{
int iKey=0;
string strPrefix;
string strPostfix;
string input_directory;
string output_file;
if(argc != 3) {
fprintf(stderr, "%s output_info.txt raw/data/directory/\n", argv[0]);
return -1;
}
input_directory = argv[2];
output_file = argv[1];
/* Get a file listing of all files with in the input directory */
DIR *dir_p = opendir (input_directory.c_str());
struct dirent *dir_entry_p;
if(dir_p == NULL) {
fprintf(stderr, "Failed to open directory %s\n", input_directory.c_str());
return -1;
}
fprintf(stderr, "Object Marker: Input Directory: %s Output File: %s\n", input_directory.c_str(), output_file.c_str());
// init highgui
cvAddSearchPath(input_directory);
cvNamedWindow(window_name,1);
cvSetMouseCallback(window_name,on_mouse, NULL);
fprintf(stderr, "Opening directory...");
// init output of rectangles to the info file
ofstream output(output_file.c_str());
fprintf(stderr, "done.\n");
while((dir_entry_p = readdir(dir_p)) != NULL)
{
numOfRec=0;
if(strcmp(dir_entry_p->d_name, ""))
fprintf(stderr, "Examining file %s\n", dir_entry_p->d_name);
/* TODO: Assign postfix/prefix info */
strPostfix="";
strPrefix=input_directory;
strPrefix+=dir_entry_p->d_name;
//strPrefix+=bmp_file.name;
fprintf(stderr, "Loading image %s\n", strPrefix.c_str());
if((image=cvLoadImage(strPrefix.c_str(),1)) != 0)
{
// work on current image
do
{
cvShowImage(window_name,image);
// used cvWaitKey returns:
// <Enter>=13 save added rectangles and show next image
// <ESC>=27 exit program
// <Space>=32 add rectangle to current image
// any other key clears rectangle drawing only
iKey=cvWaitKey(0);
switch(iKey)
{
case 27:
cvReleaseImage(&image);
cvDestroyWindow(window_name);
return 0;
case 32:
numOfRec++;
printf(" %d. rect x=%d\ty=%d\tx2h=%d\ty2=%d\n",numOfRec,roi_x0,roi_y0,roi_x1,roi_y1);
//printf(" %d. rect x=%d\ty=%d\twidth=%d\theight=%d\n",numOfRec,roi_x1,roi_y1,roi_x0-roi_x1,roi_y0-roi_y1);
// currently two draw directions possible:
// from top left to bottom right or vice versa
if(roi_x0<roi_x1 && roi_y0<roi_y1)
{
printf(" %d. rect x=%d\ty=%d\twidth=%d\theight=%d\n",numOfRec,roi_x0,roi_y0,roi_x1-roi_x0,roi_y1-roi_y0);
// append rectangle coord to previous line content
strPostfix+=" "+IntToString(roi_x0)+" "+IntToString(roi_y0)+" "+IntToString(roi_x1-roi_x0)+" "+IntToString(roi_y1-roi_y0);
}
if(roi_x0>roi_x1 && roi_y0>roi_y1)
{
printf(" %d. rect x=%d\ty=%d\twidth=%d\theight=%d\n",numOfRec,roi_x1,roi_y1,roi_x0-roi_x1,roi_y0-roi_y1);
// append rectangle coord to previous line content
strPostfix+=" "+IntToString(roi_x1)+" "+IntToString(roi_y1)+" "+IntToString(roi_x0-roi_x1)+" "+IntToString(roi_y0-roi_y1);
}
break;
}
}
while(iKey!=13);
// save to info file as later used for HaarTraining:
// <rel_path>\bmp_file.name numOfRec x0 y0 width0 height0 x1 y1 width1 height1...
if(numOfRec>0 && iKey==13)
{
//append line
/* TODO: Store output information. */
output << strPrefix << " "<< numOfRec << strPostfix <<"\n";
}
cvReleaseImage(&image);
} else {
fprintf(stderr, "Failed to load image, %s\n", strPrefix.c_str());
}
}
output.close();
cvDestroyWindow(window_name);
closedir(dir_p);
return 0;
}

read event never triggered, using libevent

I just write an echo server using libevent, but it seems that the read event is never triggered. The code is:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/tcp.h>
#include <event.h>
#include <event2/event.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
static short ListenPort = 19999;
static long ListenAddr = INADDR_ANY;//任意地址,值就是0
static int MaxConnections = 1024;
static int ServerSocket;
static struct event ServerEvent;
int SetNonblock(int fd)
{
int flags;
if ((flags = fcntl(fd, F_GETFL)) == -1) {
return -1;
}
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
return -1;
}
return 0;
}
void ServerRead(int fd, short ev, void *arg)
{
//1)when telnet on 1999 and send a string,this never prints,help!
printf("client readble\n");
fflush(stdout);
struct client *client = (struct client *)arg;
u_char buf[8196];
int len, wlen;
len = read(fd, buf, sizeof(buf));
if (len == 0) {
printf("disconnected\n");
close(fd);
event_del(&ServerEvent);
free(client);
return;
} else if (len < 0) {
printf("socket fail %s\n", strerror(errno));
close(fd);
event_del(&ServerEvent);
free(client);
return;
}
wlen = write(fd, buf, len);//1)client str never echo back
if (wlen < len) {
printf("not all data write back to client\n");
}
}
void ServerWrite(int fd, short ev, void *arg)
{
//2)to be simple,let writer do nothing
/* if(!arg)
{
printf("ServerWrite err!arg null\n");
return;
}
int len=strlen(arg);
if(len <= 0)
{
printf("ServerWrite err!len:%d\n",len);
return;
}
int wlen = write(fd, arg, len);
if (wlen<len) {
printf("not all data write back to client!wlen:%d len:%d \n",wlen,len);
}
*/
return;
}
void ServerAccept(int fd, short ev, void *arg)
{
int cfd;
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
int yes = 1;
cfd = accept(fd, (struct sockaddr *)&addr, &addrlen);
if (cfd == -1) {
//3)this prints ok
printf("accept(): can not accept client connection");
return;
}
if (SetNonblock(cfd) == -1) {
close(cfd);
return;
}
if (setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == -1) {
printf("setsockopt(): TCP_NODELAY %s\n", strerror(errno));
close(cfd);
return;
}
event_set(&ServerEvent, cfd, EV_READ | EV_PERSIST, ServerRead, NULL);
event_set(&ServerEvent, cfd, EV_WRITE| EV_PERSIST, ServerWrite,NULL);
event_add(&ServerEvent, NULL);
printf("Accepted connection from %s \n", (char *)inet_ntoa(addr.sin_addr));
}
int NewSocket(void)
{
struct sockaddr_in sa;
ServerSocket = socket(AF_INET, SOCK_STREAM, 0);
if (ServerSocket == -1) {
printf("socket(): can not create server socket\n");
return -1;
}
if (SetNonblock(ServerSocket) == -1) {
return -1;
}
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(ListenPort);
sa.sin_addr.s_addr = htonl(ListenAddr);
if (bind(ServerSocket, (struct sockaddr*)&sa, sizeof(sa)) == -1) {
close(ServerSocket);
printf("bind(): can not bind server socket");
return -1;
}
if (listen(ServerSocket, MaxConnections) == -1) {
printf("listen(): can not listen server socket");
close(ServerSocket);
return -1;
}
event_set(&ServerEvent, ServerSocket, EV_READ | EV_PERSIST, ServerAccept, NULL);
if (event_add(&ServerEvent, 0) == -1) {
printf("event_add(): can not add accept event into libevent");
close(ServerSocket);
return -1;
}
return 0;
}
int main(int argc, char *argv[])
{
int retval;
event_init();
retval = NewSocket();
if (retval == -1) {
exit(-1);
}
event_dispatch();
return 0;
}
The server is tested using Telnet, but the client receives nothing.
The question details are posted as comments in the code above, at 1)、2)、3).
Can someone help me find out why the read event is never triggered?
basically you should not set the accepted socket as EV_WRITE until you actually want to write to the socket. You are telling libevent "let me know when I can write to this socket", which is pretty much always. So ServerWrite is being called in a tight loop. In practice the only time you need EV_WRITE is if you are writing a buffer but all of the bytes are not written. You then need to save the unwritten portion of the buffer and use EV_WRITE to signal when the socket can be written to again.

Resources