snprintf and sscanf

snprintf and sscanf


Neelkanth_221$ cat sscanf.c
#include <stdio.h>

#define IFNAMSIZ  16
#define ETHER_ADDR_STR_LEN  18

void main(void)
{
    char  ifname[IFNAMSIZ + 1]               = "eth0";
    char   sta_mac_ea[ETHER_ADDR_STR_LEN]    = "11:11:11:11:12:32";
    unsigned int event_type                  = 123;

    char a[256] = {0};

    snprintf(a, sizeof(a), "%s %s %d", ifname, sta_mac_ea, event_type);

    printf("######### After snprintf ############\n");
    printf("%s\n", a);

    char  ifname_1[IFNAMSIZ + 1]             = {0};
    char   sta_mac_ea_1[ETHER_ADDR_STR_LEN]  = {0};
    unsigned int event_type_1                = 0;

    sscanf(a, "%s %s %d", ifname_1, sta_mac_ea_1, &event_type_1);

    printf("######### After sscanf ############\n");
    printf("%d\n", event_type_1);
    printf("%s\n", sta_mac_ea_1);
    printf("%s\n", ifname_1);


    return;
}


Neelkanth_221$ ./a.out

######### After snprintf ############
eth0 11:11:11:11:12:32 123
######### After sscanf ############
123
11:11:11:11:12:32
eth0

C program to copy data from structure into array and from array back into another structure

C program to copy data from structure into array and from array back into another structure


#include <stdio.h>
#include <unistd.h>
#include <string.h>

/*
 * copy a structure into array (memcpy)
 * copy an array into structure (memcpy)
 * retrieve structure's parameters
 */

struct temp {
    char a[100];
    char b[21];
    char c[32];
};

int main()
{
    char a[500];

    struct temp temp1;

    strcpy(temp1.a, "roger federer");
    strcpy(temp1.b, "rafael nadal");
    strcpy(temp1.c, "novak djokovic");

    struct temp temp2;

    memcpy(a, &temp1, sizeof(struct temp));

    memcpy(&temp2, a, sizeof(struct temp));
    printf("%s \n%s \n%s\n",  temp2.a, temp2.b, temp2.c);

    return 0;
}


Neelkanth_221$ ./a.out

roger federer
rafael nadal
novak djokovic

Complete procedure on how to use "gcov" code coverage tool in linux

#############################
How to test gcov in linux
#############################

##############################################################Step 1: Compile an image with the below flags and make sure that the process runs infinitely.##############################################################

gcc -Wall -fprofile-arcs -ftest-coverage hello.c -o hello

################################################################Step 2: Get the PID of the process that is running "infinitely" ################################################################

Neelkanth_221$ ps -elf | grep hello
0 R labuser  21036  5897 99  80   0 -  1056 -      20:53 pts/14   00:02:18 ./hello
0 S labuser  21047 20631  0  80   0 -  3989 pipe_w 20:56 pts/16   00:00:00 grep --color=auto hello

####################################################################
Step 3: Issue SIGUSR1 signal to the "pid" of the process for which
we will be running gcov.
####################################################################

kill -SIGUSR1 21055


####################################################################Step 4: hello.gcno file would be generated. do gcov <hello.gcno> to get the gcov report ####################################################################

hello.gcno
Neelkanth_221$ gcov hello.gcno
File 'hello.c'
Lines executed:93.33% of 15
Creating 'hello.c.gcov'


#####################################################################                  Sample "hello.c" code for gcov#####################################################################

/*
 * dumping gcov data at runtime - note: no error handling to keep it simple
 */
/*
 * Compile: gcc -Wall -fprofile-arcs -ftest-coverage hello.c -o hello
 * Run: ./hello &
 *      kill -s SIGUSR1 `pidof hello`
 *
 */
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

static unsigned long long i = 0;
void __gcov_flush(void); /* check in gcc sources gcc/gcov-io.h for the prototype */

void my_handler(int signum)
{
    printf("received signal\n");
    printf("%llu\n", i);
    __gcov_flush(); /* dump coverage data on receiving SIGUSR1 */
}

int main(int argc, char **argv)
{
    struct sigaction new_action, old_action;
    int n;

    /* setup signal hander */
    new_action.sa_handler = my_handler;
    sigemptyset(&new_action.sa_mask);
    new_action.sa_flags = 0;

    sigaction(SIGUSR1, NULL, &old_action);
    if (old_action.sa_handler != SIG_IGN)
        sigaction (SIGUSR1, &new_action, NULL);

    /* infinite loop - to exemplify dumping coverage data while program runs */
    for(n = 0; ; n++) {
        i++;

        if (0) {
            printf("roger federer\n");
        }
        if (0) {
            printf("roger federer\n");
        }
        if (0) {
            printf("roger federer\n");
        }
        if (0) {
            printf("roger federer\n");
        }
        if (0) {
            printf("roger federer\n");
        }

    }

}


The Four Stages of Compiling a C Program

Compiling a C program is a multi-stage process. At an overview level, the process can be split into four separate stages: Preprocessing, compilation, assembly, and linking.


/*
 * "Hello, World!": A classic.
 */

#include <stdio.h>

int
main(void)
{
puts("Hello, World!");
return 0;
}

Preprocessing

The first stage of compilation is called preprocessing. In this stage, lines starting with a # character are interpreted by the preprocessor as preprocessor commands. These commands form a simple macro language with its own syntax and semantics. This language is used to reduce repetition in source code by providing functionality to inline files, define macros, and to conditionally omit code.

Before interpreting commands, the preprocessor does some initial processing. This includes joining continued lines (lines ending with a \) and stripping comments.

To print the result of the preprocessing stage, pass the -E option to cc:

cc -E hello_world.c
Given the “Hello, World!” example above, the preprocessor will produce the contents of the stdio.h header file joined with the contents of the hello_world.c file, stripped free from its leading comment:

[lines omitted for brevity]

extern int __vsnprintf_chk (char * restrict, size_t,
       int, size_t, const char * restrict, va_list);
# 493 "/usr/include/stdio.h" 2 3 4
# 2 "hello_world.c" 2

int
main(void) {
 puts("Hello, World!");
 return 0;
}

Compilation

The second stage of compilation is confusingly enough called compilation. In this stage, the preprocessed code is translated to assembly instructions specific to the target processor architecture. These form an intermediate human readable language.

The existence of this step allows for C code to contain inline assembly instructions and for different assemblers to be used.

Some compilers also supports the use of an integrated assembler, in which the compilation stage generates machine code directly, avoiding the overhead of generating the intermediate assembly instructions and invoking the assembler.

To save the result of the compilation stage, pass the -S option to cc:

cc -S hello_world.c
This will create a file named hello_world.s, containing the generated assembly instructions. On macOS 10.10.4, where cc is an alias for clang, the following output is generated:

    .section    __TEXT,__text,regular,pure_instructions
    .macosx_version_min 10, 10
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp0:
    .cfi_def_cfa_offset 16
Ltmp1:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp2:
    .cfi_def_cfa_register %rbp
    subq    $16, %rsp
    leaq    L_.str(%rip), %rdi
    movl    $0, -4(%rbp)
    callq   _puts
    xorl    %ecx, %ecx
    movl    %eax, -8(%rbp)          ## 4-byte Spill
    movl    %ecx, %eax
    addq    $16, %rsp
    popq    %rbp
    retq
    .cfi_endproc

    .section    __TEXT,__cstring,cstring_literals
L_.str:                                 ## @.str
    .asciz  "Hello, World!"


.subsections_via_symbols


Assembly

During this stage, an assembler is used to translate the assembly instructions to object code. The output consists of actual instructions to be run by the target processor.

To save the result of the assembly stage, pass the -c option to cc:

cc -c hello_world.c
Running the above command will create a file named hello_world.o, containing the object code of the program. The contents of this file is in a binary format and can be inspected using hexdump or od by running either one of the following commands:

hexdump hello_world.o
od -c hello_world.o

Linking

The object code generated in the assembly stage is composed of machine instructions that the processor understands but some pieces of the program are out of order or missing. To produce an executable program, the existing pieces have to be rearranged and the missing ones filled in. This process is called linking.

The linker will arrange the pieces of object code so that functions in some pieces can successfully call functions in other ones. It will also add pieces containing the instructions for library functions used by the program. In the case of the “Hello, World!” program, the linker will add the object code for the puts function.

The result of this stage is the final executable program. When run without options, cc will name this file a.out. To name the file something else, pass the -o option to cc:

cc -o hello_world hello_world.c

13. Linux Kernel Driver Program: 7_Network device driver

13. Linux Kernel Driver Program: 7_Network device driver

/*
 * Building a Basic Network Driver Stub
 *
 * Write a basic network device driver.
 *
 * It should register itself upon loading, and unregister upon
 * removal.
 *
 * Supply minimal open() and stop() methods.
 *
 * You should be able to exercise it with:
 *
 *     insmod lab1_network.ko
 *     ifconfig mynet0 up 192.168.3.197
 *     ifconfig mynet0
 *
 * Make sure your chosen address is not being used by anything else.
 *
 * Warning: Depending on kernel version, your stub driver may crash if
 * you try to bring it up or ping it.  If you put in a trivial
 * transmit function, such as
 *
 * static int stub_start_xmit (struct sk_buff *skb, struct net_device *dev)
 * {
 *   dev_kfree_skb (skb);
 *   return 0;
 * }
 * this should avoid the problems.
 *
 @*/
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/init.h>

static struct net_device *dev;

static int my_open(struct net_device *dev)
{
 pr_info("Hit: my_open(%s)\n", dev->name);

 /* start up the transmission queue */

 netif_start_queue(dev);
 return 0;
}

static int my_close(struct net_device *dev)
{
 pr_info("Hit: my_close(%s)\n", dev->name);

 /* shutdown the transmission queue */

 netif_stop_queue(dev);
 return 0;
}

/* Note this method is only needed on some; without it
   module will fail upon removal or use. At any rate there is a memory
   leak whenever you try to send a packet through in any case*/

static int stub_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
 dev_kfree_skb(skb);
 return 0;
}

static struct net_device_ops ndo = {
 .ndo_open = my_open,
 .ndo_stop = my_close,
 .ndo_start_xmit = stub_start_xmit,
};

static void my_setup(struct net_device *dev)
{
 int j;
 pr_info("my_setup(%s)\n", dev->name);

 /* Fill in the MAC address with a phoney */

 for (j = 0; j < ETH_ALEN; ++j) {
  dev->dev_addr[j] = (char)j;
 }

 ether_setup(dev);
 dev->netdev_ops = &ndo;
}

static int __init my_init(void)
{
 pr_info("Loading stub network module:....");
 dev = alloc_netdev(0, "mynet%d", my_setup);
 if (register_netdev(dev)) {
  pr_info(" Failed to register\n");
  free_netdev(dev);
  return -1;
 }
 pr_info("Succeeded in loading %s!\n\n", dev_name(&dev->dev));
 return 0;
}

static void __exit my_exit(void)
{
 pr_info("Unloading stub network module\n\n");
 unregister_netdev(dev);
 free_netdev(dev);
}

module_init(my_init);
module_exit(my_exit);

MODULE_AUTHOR("Bill Shubert");
MODULE_AUTHOR("Jerry Cooperstein");
MODULE_AUTHOR("Tatsuo Kawasaki");
MODULE_DESCRIPTION("LDD:2.0 s_24/lab1_network.c");
MODULE_LICENSE("GPL v2");

Filters for Wi-Fi Management frames in Wireshark (monitor mode)

Association Request
(wlan.fc.type == 0)&&(wlan.fc.type_subtype == 0x00)

Association Response
(wlan.fc.type == 0)&&(wlan.fc.type_subtype == 0x01)

Reassociation Request
(wlan.fc.type == 0)&&(wlan.fc.type_subtype == 0x02)

Reassociation Response
(wlan.fc.type == 0)&&(wlan.fc.type_subtype == 0x03)

Probe Request
(wlan.fc.type == 0)&&(wlan.fc.type_subtype == 0x04)

Probe Response
(wlan.fc.type == 0)&&(wlan.fc.type_subtype == 0x05)

Beacon
(wlan.fc.type == 0)&&(wlan.fc.type_subtype == 0x08)

Announcement Traffic Indication Message – ATIM
(wlan.fc.type == 0)&&(wlan.fc.type_subtype == 0x09)

Disasociation
(wlan.fc.type == 0)&&(wlan.fc.type_subtype == 0x0a)

Authentication
(wlan.fc.type == 0)&&(wlan.fc.type_subtype == 0x0b)

Deauthentication
(wlan.fc.type == 0)&&(wlan.fc.type_subtype == 0x0c)

Action
(wlan.fc.type == 0)&&(wlan.fc.type_subtype == 0x0d)

Action No ACK
(wlan.fc.type == 0)&&(wlan.fc.type_subtype == 0x0e)

Performing Wi-Fi channel scan on Raspberry pi for AP's

How does a Wireless client discover Wireless Router ??

The IEEE 802.11 standards define two methods for a client device to discover wireless networks in the area. Both methods are based on using 802.11 management frames as defined in these standards.
The first method is a passive method. All 802.11 infrastructure devices will send out a beacon frame approximately every 100ms (this is the default for many devices, but often can be configured either higher or lower) for each wireless network that provides service at the time. These beacon frames will contain information about the wireless network such as the SSID (aka network name), encryption details (if any), supported data rates, etc.
Wireless clients that are in the area will be able to "hear" the beacon and know the network is in the area.
The second method is an active method, and is the one most often used by operating systems. The client device can send a probe request frame either generally ("Is anyone out there?") or to a specific network ("Hey, Bill, are you out there?"). An access point (any in the first case, matching ones in the second) will respond to this probe request with a probe response that will contain information similar to a beacon frame.
This probe request/probe response process is also part of the association process by which a station joins a wireless network.
The reason that the active method is generally preferred by most operating systems is obvious when one sits down to think about it. To discover a network passively, the device will have to listen on a channel long enough to stand a good chance of hearing a beacon frame. Since a beacon is only sent every period of time, a device may have to listen (and only listen) for 200ms or more to make sure they hear all the networks. If you only consider 2.4GHz, that is at least 11 channels...do the math.
The active method allows a station to switch to a channel, send a probe request, pause briefly (less than 100ms) and then move to the next channel. This makes this a faster process while still being fairly confident it has found the networks on that channel.


Neelkanth $:iwlist frequency

eth0      no frequency information.
          Channel 01 : 2.412 GHz
          Channel 02 : 2.417 GHz
          Channel 03 : 2.422 GHz
          Channel 04 : 2.427 GHz
          Channel 05 : 2.432 GHz
          Channel 06 : 2.437 GHz
          Channel 07 : 2.442 GHz
          Channel 08 : 2.447 GHz
          Channel 09 : 2.452 GHz
          Channel 10 : 2.457 GHz
          Channel 11 : 2.462 GHz
lo        no frequency information.

wlan0     11 channels in total; available frequencies :
          Current Frequency:2.427 GHz (Channel 4)

Neelkanth $:iwconfig

eth0      no wireless extensions.

lo        no wireless extensions.

wlan0     IEEE 802.11  ESSID:"sparrow"  
          Mode:Managed  Frequency:2.427 GHz  Access Point: 1C:67:58:72:5C:04   
          Bit Rate=72.2 Mb/s   Tx-Power=31 dBm   
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:on
          Link Quality=44/70  Signal level=-66 dBm  
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:0  Invalid misc:0   Missed beacon:0

Usage: iwconfig [interface]
                interface essid                    {NNN|any|on|off}
                interface mode                  {managed|ad-hoc|master|...}
                interface                           freq N.NNN[k|M|G]
                interface                           channel N
                interface                           bit {N[k|M|G]|auto|fixed}
                interface                           rate {N[k|M|G]|auto|fixed}
                interface                           enc {NNNN-NNNN|off}
                interface                           key {NNNN-NNNN|off}
                interface                           power {period N|timeout N|saving N|off}
                interface                           nickname NNN
                interface                           nwid {NN|on|off}
                interface                           ap {N|off|auto}
                interface                           txpower {NmW|NdBm|off|auto}
                interface                           sens N
                interface                           retry {limit N|lifetime N}
                interface                           rts {N|auto|fixed|off}
                interface                           frag {N|auto|fixed|off}
                interface                           modulation {11g|11a|CCK|OFDMg|...}
                interface commit 

Neelkanth $:iwlist auth

eth0      no authentication information.

lo        no authentication information.

wlan0     Authentication capabilities :
WPA
WPA2
CIPHER-TKIP
CIPHER-CCMP

Neelkanth $:iwlist event

eth0      no wireless event capability information.

lo        no wireless event capability information.

wlan0     Wireless Events supported :
          0x8B04 : Set Frequency/Channel (kernel generated)
          0x8B06 : Set Mode (kernel generated)
          0x8B15 : New Access Point/Cell address - roaming
          0x8B19 : Scan request completed
          0x8B1A : Set ESSID (kernel generated)
          0x8B2A : Set Encoding (kernel generated)

wlan0     Scanning capabilities :
- ESSID


Neelkanth $:iwlist power

eth0      no power management information.

lo        no power management information.

wlan0     Current mode:on

Neelkanth $:iwlist txpower

eth0      no transmit-power information.

lo        no transmit-power information.

wlan0     unknown transmit-power information.

          Current Tx-Power=31 dBm   (1258 mW)


Neelkanth $:sudo iwlist wlan0 scan 

wlan0     Scan completed :
          Cell 01 - Address: 1C:67:58:72:5C:04
                    Channel:4
                    Frequency:2.427 GHz (Channel 4)
                    Quality=46/70  Signal level=-64 dBm  
                    Encryption key:on
                    ESSID:"sparrow"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s
                              24 Mb/s; 36 Mb/s; 54 Mb/s
                    Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 48 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 30ms ago
                    IE: Unknown: 000773706172726F77
                    IE: Unknown: 010882848B962430486C
                    IE: Unknown: 030104
                    IE: Unknown: 050400010000
                    IE: Unknown: 2A0104
                    IE: Unknown: 2F0104
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK
                    IE: Unknown: 32040C121860
                    IE: Unknown: 2D1AFC181BFFFF000000000000000000000000000000000000000000
                    IE: Unknown: 3D1604000400000000000000000000000000000000000000
                    IE: Unknown: 4A0E14000A002C01C800140005001900
                    IE: Unknown: 7F0101
                    IE: Unknown: DD180050F204104A00011010440001021049000600372A000120
                    IE: Unknown: DD090010180206F02C0000
                    IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00
          Cell 02 - Address: 0C:D2:B5:94:6F:1B
                    Channel:11
                    Frequency:2.462 GHz (Channel 11)
                    Quality=25/70  Signal level=-85 dBm  
                    Encryption key:on
                    ESSID:"nas2013"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                              9 Mb/s; 12 Mb/s; 18 Mb/s
                    Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 30ms ago
                    IE: Unknown: 00076E617332303133
                    IE: Unknown: 010882848B960C121824
                    IE: Unknown: 03010B
                    IE: Unknown: 2A0100
                    IE: Unknown: 32043048606C
                    IE: Unknown: 2D1AEF191FFFFF000000000000000000000000000000001804810800
                    IE: Unknown: 3D160B000000000000000000000000000000000000000000
                    IE: Unknown: 4A0E14000A00B400C800140005001900
                    IE: WPA Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK
                    IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00
                    IE: Unknown: DD1E00904C33EF191FFFFF000000000000000000000000000000001804810800
                    IE: Unknown: DD1A00904C340B000000000000000000000000000000000000000000
                    IE: Unknown: DD0600E04C020160
                    IE: Unknown: 7F080100000000000000
          Cell 03 - Address: E8:94:F6:4A:24:30
                    Channel:6
                    Frequency:2.437 GHz (Channel 6)
                    Quality=18/70  Signal level=-92 dBm  
                    Encryption key:on
                    ESSID:"THIRUMALAI"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s
                              24 Mb/s; 36 Mb/s; 54 Mb/s
                    Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 48 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 23060ms ago
                    IE: Unknown: 000A54484952554D414C4149
                    IE: Unknown: 010882848B962430486C
                    IE: Unknown: 030106
                    IE: Unknown: 2A0100
                    IE: Unknown: 2F0100
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK
                    IE: Unknown: 32040C121860
                    IE: Unknown: 2D1AFE191BFFFF000001000000000000000000000000000000000000
                    IE: Unknown: 3D16060D0000000000000000000000000000000000000000
                    IE: Unknown: DD8E0050F204104A0001101044000102103B000103104700107CCBF78E6D00644555719E97E775ED791021000754502D4C494E4B10230009544C2D57523834304E10240006313233343536104200033030311054000800060050F204000110110019576972656C65737320526F7574657220544C2D57523834304E100800022008103C0001011049000600372A000120
                    IE: Unknown: DD090010180200F02C0000
                    IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00
          Cell 04 - Address: 18:A6:F7:FE:09:A2
                    Channel:9
                    Frequency:2.452 GHz (Channel 9)
                    Quality=55/70  Signal level=-55 dBm  
                    Encryption key:on
                    ESSID:"Neel_Ironman_priv"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                              9 Mb/s; 12 Mb/s; 18 Mb/s
                    Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=0000000000000000
                    Extra: Last beacon: 30ms ago
                    IE: Unknown: 00114E65656C5F49726F6E6D616E5F70726976
                    IE: Unknown: 010882848B960C121824
                    IE: Unknown: 030109
                    IE: Unknown: 2A0100
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK
                    IE: Unknown: 32043048606C
                    IE: Unknown: 2D1A6F111BFF00000000000000000000000100000000000000000000
                    IE: Unknown: 3D16090F0000000000000000000000000000000000000000
                    IE: Unknown: 7F080000000000000040
                    IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00
                    IE: Unknown: DD0900037F01010000FF7F
                    IE: Unknown: DDA90050F204104A0001101044000102103B00010310470010000102030405060708090A0B0C0D0E0F1021000754502D4C494E4B10230014544C2D57523734304E2F544C2D57523734314E4410240003362E3010420003312E301054000800060050F20400011011001E576972656C65737320526F757465722057523734304E2F57523734314E44100800020086103C000101104900140024E26002000101600000020001600100020001