Tag Archives: C++

C++ std map

Declare

std::map first;

Add
first[‘a’]=10;
first[‘b’]=30;
first[‘c’]=50;
first[‘d’]=70;

Test key exist:
if ( first.find(“f”) == first.end() ) {
// not found
} else {
// found
}

it = mymap.begin();
while (it != mymap.end()) {
   if (something)
      mymap.erase(it++);
   else
      it++;
}

C++ 11

std::map<K, V>::iterator itr = myMap.begin();
while (itr != myMap.end()) {
    if (ShouldDelete(*itr)) {
       itr = myMap.erase(itr);
    } else {
       ++itr;
    }
}

C++ Get current hour, minutes of the day

#include <time.h>
time_t theTime = time(NULL);
struct tm *aTime = localtime(&theTime);

int day = aTime->tm_mday;
int month = aTime->tm_mon + 1; // Month is 0 – 11, add 1 to get a jan-dec 1-12 concept
int year = aTime->tm_year + 1900; // Year is # years since 1900
int hour=aTime->tm_hour;
int min=aTime->tm_min;

std::list example:: iterate list

Two ways to iterate list

1. use this one when need to remove item from the list.

	std::list<int>::iterator it = m_clientList.begin();

		while (it != m_clientList.end()) {
			if (xxxx) {
				it = m_clientList.erase(it);
			} else {
				++it;
			}
		}

2. normal iterate

list<int> copylist = GetClients();
		for (std::list<int>::iterator it = copylist.begin();
				it != copylist.end(); ++it) {
			int n = *it;
//do something with n 
		}

dhcp query libnet

/* Ultra-fast dhcp discovery
*
* $Id: dhcp_discover.c,v 2004/01/03 20:31:01 mike Exp $
* dhd.c,v LatinSuD 2006
*
* Compile:
* gcc -o dhd dhd.c -lnet -lpcap -lpthread
*
* Example usage:
* dhd
* dhd eth0
*
* Example output:
* #0:
* SERVER-MAC: 00:01:38:12:34:56
* IP: 192.168.1.1
* CLIENT-MAC: 00:0e:35:ab:cd:ef
* IP: 192.168.1.40
*
* >> "0 "0
*
* Dhd injects 10 dhcp requests on interface. In this case,
* it has been received a response, numbered as "0".
* Later, response 0 was received twice more.
*/

#define DHD_VERSION "2.1"

/*
* Changes:
* 2.1 (2007-04-07):
* - Identify equivalent packets with different time fields
* - Add domain-suffix field
* - Minor cleanup & enhanced usage help
*
* 2.0 (2006-??-??):
* - Beautify printf
*
* libnet 1.1
* Build a DHCP discover packet
* To view: /usr/sbin/tcpdump -vvvvven -s 4096 'port 67 or port 68'
*
* Copyright (c) 1998 - 2004 Mike D. Schiffman
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/

#include
#include #include
#include #include
#include
#include #include

/* Ethernet addresses are 6 bytes */
#ifndef ETHER_ADDR_LEN
#define ETHER_ADDR_LEN 6
#endif

/* Ethernet header */
struct sniff_ethernet {
u_char ether_dhost[ETHER_ADDR_LEN]; /* Destination host address */
u_char ether_shost[ETHER_ADDR_LEN]; /* Source host address */
u_short ether_type; /* IP? ARP? RARP? etc */
};

/* IP header */
struct sniff_ip {
u_char ip_vhl; /* version << 4 | header length >> 2 */
u_char ip_tos; /* type of service */
u_short ip_len; /* total length */
u_short ip_id; /* identification */
u_short ip_off; /* fragment offset field */
u_char ip_ttl; /* time to live */
u_char ip_p; /* protocol */
u_short ip_sum; /* checksum */
struct in_addr ip_src, ip_dst; /* source and dest address */
};

typedef struct {
u_short uh_sport; /* source port */
u_short uh_dport; /* destination port */

u_short len;
u_short chk;

unsigned char type;
char a;
char b;
char c;
u_short d;
u_short e;
} sniff_udp;

/* ethernet headers are always exactly 14 bytes */
int SIZE_ETHERNET = 14;
#define IP_HL(ip) (((ip)->ip_vhl) & 0x0f)
#define IP_V(ip) (((ip)->ip_vhl) >> 4)

const struct sniff_ethernet *ethernet; /* The ethernet header */
struct sniff_ip *ip; /* The IP header */
const struct sniff_tcp *tcp; /* The TCP header */
const char *payload; /* Packet payload */

pthread_t sniffer, injector;

void print_mac(unsigned char *packet, int moffset)
{
int i;
if (moffset > 80)
exit(0);
for (i = 0; i < 6; i++) printf("%02x%c", packet[i + moffset], (i < 5) ? ':' : '\0'); } void print_ip(unsigned char *ip, int offset) { int i; for (i = 0; i < 4; i++) { printf("%d", ip[i + offset]); if (i < 3) printf("."); } } #define DNS 0 #define MASK 1 #define CIP 2 #define SIP 3 #define GW 4 int didCR = 1; #define HASH 8 #define PCACHE 256 int h_pack[PCACHE]; int n_pack = 0; unsigned int miChecksum(u_char * packet, int len) { int i; int s1 = 0; int s2 = 0; u_char * ptr=packet; while (ptr - packet < len - 1) { if (ptr - packet + ptr[1] + 2 > len)
break;

// ignore time dependent fields
if (ptr[0]==2 || ptr[0]==51 || ptr[0]==58 || ptr[0]==59) {
ptr += 2 + ptr[1];
continue;
}

for (i = 0; i < ptr[1]+2; i++) { s1 += ptr[i] * i; s2 += ptr[i]; } ptr += 2 + ptr[1]; } return s1 + (s2 << 16); } // Caches known packets, so they are printed only once int cache_packet(u_char * packet, int len, int *num) { int i; int hash = miChecksum(packet, len); for (i = 0; i < n_pack; i++) { if (h_pack[i] == hash) { *num = i; return 0; } } if (n_pack < PCACHE) { h_pack[n_pack] = hash; *num = n_pack; n_pack++; } return -1; } // Pcap callback that does all the work void got_packet(u_char * args, const struct pcap_pkthdr *header, const u_char * packet) { sniff_udp *udp; int i; uint size_ip; u_char *ptr; int idx; int dijoIp = 0; ethernet = (struct sniff_ethernet *) (packet); ip = (struct sniff_ip *) (packet + SIZE_ETHERNET); size_ip = (IP_HL(ip)) * 4; udp = (sniff_udp *) (packet + SIZE_ETHERNET + size_ip); if (*(((char *) udp) + 8) != 2) return; ptr = ((unsigned char *) udp) + 0xf8; if (cache_packet(ptr, header->len - (ptr - packet), &idx) == 0) {
// packet already in cache, show only reference number
if (didCR)
printf("\n >>");
printf(" \"%d ", idx);
didCR = 0;
return;
} else {
// start dissecting packet
puts("");
if (!didCR)
puts("");
printf(" #%d:\n", idx);
}

printf("\tSERVER-MAC: \x1b[1m");
print_mac((unsigned char *) packet, 6);
printf("\x1b[0m\n");

// print only known interesting fields
while (ptr - packet < header->len - 1) {
if (ptr - packet + ptr[1] + 2 > header->len)
break;

if (ptr[0] == 6) {
printf("\tDNS: \x1b[1m");
for (i = 0; i < (ptr[1] / 4); i++) { if (i != 0) printf(", "); print_ip(ptr, 2 + 4 * i); } printf("\x1b[0m\n"); } else if (ptr[0] == 1) { printf("\t MASK: \x1b[1m"); print_ip(ptr, 2); printf("\x1b[0m\n"); } else if (ptr[0] == 54) { printf("\t IP: \x1b[1m"); print_ip(ptr, 2); printf("\x1b[0m\n"); printf("\tCLIENT-MAC: \x1b[1m"); print_mac((unsigned char *) udp, 0x24); printf("\x1b[0m\n"); printf("\t IP: \x1b[1m"); print_ip((unsigned char *) udp, 0x18); printf("\x1b[0m\n"); dijoIp = 1; } else if (ptr[0] == 15) { printf("\tDOMAIN-SUFFIX: \x1b[1m"); for (i=0; i=0x20 && ptr[2+i]<0x7F)?ptr[2+i]:' '); printf("\x1b[0m\n"); } else if (ptr[0] == 3) { printf("\tGW: \x1b[1m"); print_ip(ptr, 2); printf("\x1b[0m\n"); } else if (ptr[0] == 53) { if (ptr[2] != 2) break; } ptr += 2 + ptr[1]; } if (!dijoIp) { printf("\tCLIENT-IP: \x1b[1m"); print_ip((unsigned char *) udp, 0x18); printf("\x1b[0m\n"); } didCR = 1; } void usage(char *prog) { fprintf(stderr, "DHD " DHD_VERSION " - A fast DHcp Discover tool.\nUsage: dhd [INTERFACE]\n\tIf no INTERFACE is given, it will write on all available interfaces and sniff on any.\n"); exit(1); } typedef struct { char *intf; libnet_t *l; pcap_t *pcap; struct libnet_ether_addr *ethaddr; } context; struct libnet_stats ls; u_char *options; void init_libnet(context * c) { char errbuf[LIBNET_ERRBUF_SIZE]; int i; c->l = libnet_init(LIBNET_LINK, // injection type
c->intf, // network interface
errbuf); // errbuf
if (!c->l) {
fprintf(stderr, "libnet_init: %s", errbuf);
exit(EXIT_FAILURE);
}

if ((c->ethaddr = libnet_get_hwaddr(c->l)) == NULL) {
fprintf(stderr, "libnet_get_hwaddr: %s\n", libnet_geterror(c->l));
exit(EXIT_FAILURE);
}
for (i = 0; i < 6; i++) { fprintf(stderr, "%02x", c->ethaddr->ether_addr_octet[i]);
if (i != 5) {
fprintf(stderr, ":");
}
}

}

void init_packet(context * c)
{

u_long options_len, orig_len;
int i;

libnet_ptag_t t;
libnet_ptag_t ip;
libnet_ptag_t udp;
libnet_ptag_t dhcp;

u_char options_req[] =
{ LIBNET_DHCP_SUBNETMASK, LIBNET_DHCP_BROADCASTADDR,
LIBNET_DHCP_TIMEOFFSET, LIBNET_DHCP_ROUTER, LIBNET_DHCP_DOMAINNAME,
LIBNET_DHCP_DNS,
LIBNET_DHCP_HOSTNAME
};
u_char enet_dst[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
u_char *tmp;

// build options packet
i = 0;
options_len = 3; // update total payload size

// we are a discover packet
options = malloc(3);
options[i++] = LIBNET_DHCP_MESSAGETYPE; // type
options[i++] = 1; // len
options[i++] = LIBNET_DHCP_MSGDISCOVER; // data

orig_len = options_len;
options_len += sizeof(options_req) + 2; // update total payload size

// workaround for realloc on old machines
// options = realloc(options, options_len); // resize options buffer
tmp = malloc(options_len);
memcpy(tmp, options, orig_len);
free(options);
options = tmp;

// we are going to request some parameters
options[i++] = LIBNET_DHCP_PARAMREQUEST; // type
options[i++] = sizeof(options_req); // len
memcpy(options + i, options_req, sizeof(options_req)); // data
i += sizeof(options_req);

// end our options packet
// workaround for realloc on old machines
// options = realloc(options, options_len); // resize options buffer
orig_len = options_len;
options_len += 1;
tmp = malloc(options_len);
memcpy(tmp, options, orig_len);
free(options);
options = tmp;
options[i++] = LIBNET_DHCP_END;

// make sure we are at least the minimum length, if not fill
// this could go in libnet, but we will leave it in the app for now
if (options_len + LIBNET_DHCPV4_H < LIBNET_BOOTP_MIN_LEN) { orig_len = options_len; options_len = LIBNET_BOOTP_MIN_LEN - LIBNET_DHCPV4_H; // workaround for realloc on old machines // options = realloc(options, options_len); tmp = malloc(options_len); memcpy(tmp, options, orig_len); free(options); options = tmp; memset(options + i, 0, options_len - i); } // the goodies are here dhcp = libnet_build_dhcpv4(LIBNET_DHCP_REQUEST, // opcode 1, // hardware type 6, // hardware address length 0, // hop count 0xdeadbeee, // transaction id 0, // seconds since bootstrap 0x8000, // flags 0, // client ip 0, // your ip 0, // server ip 0, // gateway ip c->ethaddr->ether_addr_octet, // client hardware addr
//unamac, // client hardware addr
NULL, // server host name
NULL, // boot file
options, // dhcp options stuck in payload since it is dynamic
options_len, // length of options
c->l, // libnet handle
0); // libnet id

// wrap it
udp = libnet_build_udp(68, // source port
67, // destination port
LIBNET_UDP_H + LIBNET_DHCPV4_H + options_len, // packet size
0, // checksum
NULL, // payload
0, // payload size
c->l, // libnet handle
0); // libnet id

// hook me up with some ipv4
ip = libnet_build_ipv4(LIBNET_IPV4_H + LIBNET_UDP_H + LIBNET_DHCPV4_H + options_len, // length
0x10, // TOS
0, // IP ID
0, // IP Frag
16, // TTL
IPPROTO_UDP, // protocol
0, // checksum
inet_addr("0.0.0.0"), // src ip
inet_addr("255.255.255.255"), // destination ip
NULL, // payload
0, // payload size
c->l, // libnet handle
0); // libnet id

// we can just autobuild since we arent doing anything tricky
t = libnet_autobuild_ethernet(enet_dst, // ethernet destination
ETHERTYPE_IP, // protocol type
c->l); // libnet handle
}

int init_pcap(char *intf)
{
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t *pcap;
struct bpf_program fp; /* The compiled filter expression */
char filter_exp[] = "udp and (port 67 or port 68)"; /* The filter expression */
bpf_u_int32 net = 0; /* The IP of our sniffing device */
setbuf(stdout, 0);

//pcap = pcap_open_offline("sample.cap", errbuf);
pcap = pcap_open_live(intf, BUFSIZ, 0, 1000, errbuf);
if (pcap == NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", "any", errbuf);
return (2);
}

if (pcap_compile(pcap, &fp, filter_exp, 0, net) == -1) {
fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp,
pcap_geterr(pcap));
return (2);
}
if (pcap_setfilter(pcap, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp,
pcap_geterr(pcap));
return (2);
}
if (pcap_datalink(pcap) == DLT_LINUX_SLL)
SIZE_ETHERNET = 16;
//if (pcap_datalink (pcap) == DLT_EN10MB);

pcap_loop(pcap, -1, got_packet, (unsigned char *) errbuf);

return (0);
}

void inyecta(context * c)
{
// write to the wire
if (libnet_write(c->l) == -1) {
fprintf(stderr, " dhd: libnet_write: %s\n", strerror(errno));
}
}

void end_libnet(context * c)
{
libnet_destroy(c->l);

// free mem
free(options);

exit(0);
}

int get_datalink(char *intf)
{
int res;
pcap_t *handle;
char buf[8192];
handle = pcap_open_live(intf, 0, 0, 0, buf);
if (!handle) {
//printf("NOP SE PUDO ABRIR [%s] : %s\n", intf, buf);
return 0;
}
res = pcap_datalink(handle);
//printf(" :%s: ", pcap_datalink_val_to_description(res));
pcap_close(handle);
return res;
}

context ifaces[16];
int nIfaces = 0;

void init_iface(char * iface) {
if (get_datalink(iface) == DLT_EN10MB) {
ifaces[nIfaces].intf = strdup(iface);
fprintf(stderr, "Injecting on %s (",
ifaces[nIfaces].intf);
init_libnet(&ifaces[nIfaces]);
fprintf(stderr, ")\n");
init_packet(&ifaces[nIfaces]);
nIfaces++;
}
}

void init_all_ifaces()
{
FILE *f;
char *i1, *i2;
char buf[1024];
f = fopen("/proc/net/dev", "r");
if (!f)
return;

while (fgets(buf, 1023, f) && nIfaces<16) { i1 = buf; while (*i1 == ' ') i1++; i2 = i1; while (*i2 != '\0') { if (*i2 == ':') { *i2 = '\0'; if (strcmp(i1, "lo")) { init_iface(i1); } } i2++; } } } void *esnifa(void *data) { fprintf(stderr, "Sniffing on %s\n", (char *) data); init_pcap((char *) data); return NULL; } int main(int argc, char *argv[]) { int i, j, dormir; if (getuid() != 0) { fprintf(stderr, "Need to be root!\n"); return -1; } setbuf(stdout, 0); dormir = 100; // init if (argc == 1) { pthread_create(&sniffer, NULL, esnifa, "any"); init_all_ifaces(); } else if (argc == 2) { if (!strcmp(argv[1],"-h") || !strcmp(argv[1],"--help")) usage(argv[0]); pthread_create(&sniffer, NULL, esnifa, (void *) argv[1]); init_iface(argv[1]); } else { fprintf(stderr, "Only 1 interface can be specified!\n"); usage(argv[0]); } // inject all packets on all ifaces for (i = 0; i < 10; i++) { usleep(dormir * 1000); for (j = 0; j < nIfaces; j++) { inyecta(&ifaces[j]); } dormir = dormir + 100; } usleep(250000); if (!didCR) puts(""); for (j = 0; j < nIfaces; j++) end_libnet(&ifaces[j]); return 0; }

lookup name from IP , pretty useless for LAN, since not NBT query. just keep for record that do not spent more time

char* name = argv[1];
sa.sin_family = AF_INET;
sa.sin_addr.s_addr=inet_addr(name);
len = sizeof (struct sockaddr_in);

char hbuf[NI_MAXHOST];

if (int r=getnameinfo((sockaddr *)&sa, len, hbuf, sizeof(hbuf),NULL, 0, NI_NAMEREQD|NI_DGRAM)!=0)
printf("could not resolve hostname %d %s",r,gai_strerror(r));
else
printf("host=%s\n", hbuf);
//EAI_AGAIN

struct hostent *hp;
long addr;

addr = inet_addr(name);
if (hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET)) {
printf("Hostname:\t%s\n", hp->h_name);
printf("Aliases:\t");
while (hp->h_aliases[0])
printf("%s ", *hp->h_aliases++);
printf("\n");
printf("Addresses:\t");
while (hp->h_addr_list[0])
printf("%s ", inet_ntoa(*(struct in_addr *) * hp->h_addr_list++));
printf("\n");
exit(0);
}

Reading routing table using C program

Reading routing table using C program
#include”sys/socket.h”
#include”sys/types.h”
#include”unistd.h”
#include”stdio.h”
#include”stdlib.h”
#include”string.h”
#include”asm/types.h”
#include”linux/netlink.h”
#include”linux/rtnetlink.h”
#include”sys/ioctl.h”
#include”net/if.h”
#include”net/route.h”

bool CAddressHelper::GetDevGateWay(string &p_sDevName,
std::list

& p_Gateways) {

//#pragma pack(2)
// Structure for sending the request
typedef struct {
struct nlmsghdr nlMsgHdr;
struct rtmsg rtMsg;
char buf[1024];
} route_request;

struct RouteInfo {
unsigned long dstAddr;
unsigned long mask;
unsigned long gateWay;
unsigned long flags;
unsigned long srcAddr;
unsigned char proto;
char ifName[IF_NAMESIZE];
};

int route_sock, i, j;
route_request NewRequest;
route_request *request = &NewRequest;
int retValue = -1, nbytes = 0, reply_len = 0;
char reply_ptr[1024];
ssize_t counter = 1024;
int count = 0;
struct rtmsg *rtp;
struct rtattr *rtap;
struct nlmsghdr *nlp;
int rtl;
struct RouteInfo route[24];
char* buf = reply_ptr;
unsigned long bufsize;

route_sock = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);

if (-1 == route_sock)
return false;

bzero(request, sizeof(route_request));

request->nlMsgHdr.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
request->nlMsgHdr.nlmsg_type = RTM_GETROUTE;
request->nlMsgHdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;

// set the routing message header
request->rtMsg.rtm_family = AF_INET;
request->rtMsg.rtm_table = RT_TABLE_MAIN; // RT_TABLE_MAIN

if ((retValue = send(route_sock, request, sizeof(route_request), 0)) < 0) { perror("send"); return false; } for (;;) { if (counter < sizeof(struct nlmsghdr)) { printf("Routing table is bigger than 1024\n"); return false; } nbytes = recv(route_sock, &reply_ptr[reply_len], counter, 0); if (nbytes < 0) { printf("Error in recv\n"); break; } if (nbytes == 0) printf("EOF in netlink\n"); nlp = (struct nlmsghdr*) (&reply_ptr[reply_len]); if (nlp->nlmsg_type == NLMSG_DONE) {
// All data has been received.
// Truncate the reply to exclude this message,
// i.e. do not increase reply_len.
break;
}

if (nlp->nlmsg_type == NLMSG_ERROR) {
printf(“Error in msg\n”);
return false;
}

reply_len += nbytes;
counter -= nbytes;

}

bufsize = reply_len;
// string to hold content of the route
// table (i.e. one entry)

// outer loop: loops thru all the NETLINK
// headers that also include the route entry
// header
nlp = (struct nlmsghdr *) buf;

for (i = -1; NLMSG_OK(nlp, bufsize); nlp = NLMSG_NEXT(nlp, bufsize))
{
// get route entry header
rtp = (struct rtmsg *) NLMSG_DATA(nlp);
// we are only concerned about the
// tableId route table
if (rtp->rtm_table != RT_TABLE_MAIN)
continue;
i++;
// init all the strings
bzero(&route[i], sizeof(struct RouteInfo));
//flags = rtp->rtm_flags;
route[i].proto = rtp->rtm_protocol;

// inner loop: loop thru all the attributes of
// one route entry
rtap = (struct rtattr *) RTM_RTA(rtp);
rtl = RTM_PAYLOAD(nlp);
for (; RTA_OK(rtap, rtl); rtap = RTA_NEXT(rtap, rtl))
{
switch (rtap->rta_type) {
// destination IPv4 address
case RTA_DST:
count = 32 – rtp->rtm_dst_len;

route[i].dstAddr = *(unsigned long *) RTA_DATA(rtap);

route[i].mask = 0xffffffff;
for (; count != 0; count–)
route[i].mask = route[i].mask << 1; printf("dst:%s \tmask:0x%x \t",CAddressHelper::IntIP2str(route[i].dstAddr).c_str(), route[i].mask); break; case RTA_GATEWAY: route[i].gateWay = *(unsigned long *) RTA_DATA(rtap); printf("gw:%s\t",CAddressHelper::IntIP2str(route[i].gateWay).c_str()); break; case RTA_PREFSRC: route[i].srcAddr = *(unsigned long *) RTA_DATA(rtap); // printf("src:%s\t", CAddressHelper::IntIP2str(route[i].srcAddr).c_str()); break; // unique ID associated with the network // interface case RTA_OIF: CAddressHelper::GetInterfaceName(*((int *) RTA_DATA(rtap)), route[i].ifName); printf("ifname %s\n", route[i].ifName); break; default: break; } } //set Flags } // Print the route records // printf("Destination\tGateway \tNetmask \tflags \tIfname \n"); // printf("———–\t——- \t——–\t——\t—— \n"); for (j = 0; j <= i; j++) { if (p_sDevName == route[j].ifName&&route[j].gateWay!=0) { Address newGate; newGate.Ip = route[j].gateWay; p_Gateways.push_back(newGate); } printf("%s \t %s \t0x%08x \t%d \t%s\n", CAddressHelper::IntIP2str(route[j].dstAddr).c_str(), CAddressHelper::IntIP2str(route[j].gateWay).c_str(), route[j].mask, route[j].flags, route[j].ifName); } return true; }

GCC Options to Request or Suppress Warnings

Options to Request or Suppress Warnings

Warnings are diagnostic messages that report constructions which are not inherently erroneous but which are risky or suggest there may have been an error.

You can request many specific warnings with options beginning `-W’, for example -Wimplicit to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning `-Wno-‘ to turn off warnings; for example, -Wno-implicit. This manual lists only one of the two forms, whichever is not the default.

The following options control the amount and kinds of warnings produced by GCC; for further, language-specific options also refer to C++ Dialect Options and Objective-C and Objective-C++ Dialect Options.

-fsyntax-only
Check the code for syntax errors, but don’t do anything beyond that.
-pedantic
Issue all the warnings demanded by strict ISO C and ISO C++; reject all programs that use forbidden extensions, and some other programs that do not follow ISO C and ISO C++. For ISO C, follows the version of the ISO C standard specified by any -std option used.

Valid ISO C and ISO C++ programs should compile properly with or without this option (though a rare few will require -ansi or a -std option specifying the required version of ISO C). However, without this option, certain GNU extensions and traditional C and C++ features are supported as well. With this option, they are rejected.

-pedantic does not cause warning messages for use of the alternate keywords whose names begin and end with `__’. Pedantic warnings are also disabled in the expression that follows __extension__. However, only system header files should use these escape routes; application programs should avoid them. See Alternate Keywords.

Some users try to use -pedantic to check programs for strict ISO C conformance. They soon find that it does not do quite what they want: it finds some non-ISO practices, but not all—only those for which ISO C requires a diagnostic, and some others for which diagnostics have been added.

A feature to report any failure to conform to ISO C might be useful in some instances, but would require considerable additional work and would be quite different from -pedantic. We don’t have plans to support such a feature in the near future.

Where the standard specified with -std represents a GNU extended dialect of C, such as `gnu89′ or `gnu99′, there is a corresponding base standard, the version of ISO C on which the GNU extended dialect is based. Warnings from -pedantic are given where they are required by the base standard. (It would not make sense for such warnings to be given only for features not in the specified GNU C dialect, since by definition the GNU dialects of C include all features the compiler supports with the given option, and there would be nothing to warn about.)
-pedantic-errors
Like -pedantic, except that errors are produced rather than warnings.
-w
Inhibit all warning messages.
-Wno-import
Inhibit warning messages about the use of `#import’.
-Wchar-subscripts
Warn if an array subscript has type char. This is a common cause of error, as programmers often forget that this type is signed on some machines. This warning is enabled by -Wall.
-Wcomment
Warn whenever a comment-start sequence `/*’ appears in a `/*’ comment, or whenever a Backslash-Newline appears in a `//’ comment. This warning is enabled by -Wall.
-Wfatal-errors
This option causes the compiler to abort compilation on the first error occurred rather than trying to keep going and printing further error messages.
-Wformat
Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense. This includes standard functions, and others specified by format attributes (see Function Attributes), in the printf, scanf, strftime and strfmon (an X/Open extension, not in the C standard) families (or other target-specific families). Which functions are checked without format attributes having been specified depends on the standard version selected, and such checks of functions without the attribute specified are disabled by -ffreestanding or -fno-builtin.

The formats are checked against the format features supported by GNU libc version 2.2. These include all ISO C90 and C99 features, as well as features from the Single Unix Specification and some BSD and GNU extensions. Other library implementations may not support all these features; GCC does not support warning about features that go beyond a particular library’s limitations. However, if -pedantic is used with -Wformat, warnings will be given about format features not in the selected standard version (but not for strfmon formats, since those are not in any version of the C standard). See Options Controlling C Dialect.

Since -Wformat also checks for null format arguments for several functions, -Wformat also implies -Wnonnull.

-Wformat is included in -Wall. For more control over some aspects of format checking, the options -Wformat-y2k, -Wno-format-extra-args, -Wno-format-zero-length, -Wformat-nonliteral, -Wformat-security, and -Wformat=2 are available, but are not included in -Wall.
-Wformat-y2k
If -Wformat is specified, also warn about strftime formats which may yield only a two-digit year.
-Wno-format-extra-args
If -Wformat is specified, do not warn about excess arguments to a printf or scanf format function. The C standard specifies that such arguments are ignored.

Where the unused arguments lie between used arguments that are specified with `$’ operand number specifications, normally warnings are still given, since the implementation could not know what type to pass to va_arg to skip the unused arguments. However, in the case of scanf formats, this option will suppress the warning if the unused arguments are all pointers, since the Single Unix Specification says that such unused arguments are allowed.
-Wno-format-zero-length
If -Wformat is specified, do not warn about zero-length formats. The C standard specifies that zero-length formats are allowed.
-Wformat-nonliteral
If -Wformat is specified, also warn if the format string is not a string literal and so cannot be checked, unless the format function takes its format arguments as a va_list.
-Wformat-security
If -Wformat is specified, also warn about uses of format functions that represent possible security problems. At present, this warns about calls to printf and scanf functions where the format string is not a string literal and there are no format arguments, as in printf (foo);. This may be a security hole if the format string came from untrusted input and contains `%n’. (This is currently a subset of what -Wformat-nonliteral warns about, but in future warnings may be added to -Wformat-security that are not included in -Wformat-nonliteral.)
-Wformat=2
Enable -Wformat plus format checks not included in -Wformat. Currently equivalent to `-Wformat -Wformat-nonliteral -Wformat-security -Wformat-y2k’.
-Wnonnull
Warn about passing a null pointer for arguments marked as requiring a non-null value by the nonnull function attribute.

-Wnonnull is included in -Wall and -Wformat. It can be disabled with the -Wno-nonnull option.
-Winit-self (C, C++, Objective-C and Objective-C++ only)
Warn about uninitialized variables which are initialized with themselves. Note this option can only be used with the -Wuninitialized option, which in turn only works with -O1 and above.

For example, GCC will warn about i being uninitialized in the following snippet only when -Winit-self has been specified:

int f()
{
int i = i;
return i;
}

-Wimplicit-int
Warn when a declaration does not specify a type. This warning is enabled by -Wall.
-Wimplicit-function-declaration
-Werror-implicit-function-declaration
Give a warning (or error) whenever a function is used before being declared. The form -Wno-error-implicit-function-declaration is not supported. This warning is enabled by -Wall (as a warning, not an error).
-Wimplicit
Same as -Wimplicit-int and -Wimplicit-function-declaration. This warning is enabled by -Wall.
-Wmain
Warn if the type of `main’ is suspicious. `main’ should be a function with external linkage, returning int, taking either zero arguments, two, or three arguments of appropriate types. This warning is enabled by -Wall.
-Wmissing-braces
Warn if an aggregate or union initializer is not fully bracketed. In the following example, the initializer for `a’ is not fully bracketed, but that for `b’ is fully bracketed.

int a[2][2] = { 0, 1, 2, 3 };
int b[2][2] = { { 0, 1 }, { 2, 3 } };

This warning is enabled by -Wall.
-Wmissing-include-dirs (C, C++, Objective-C and Objective-C++ only)
Warn if a user-supplied include directory does not exist.
-Wparentheses
Warn if parentheses are omitted in certain contexts, such as when there is an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often get confused about. Only the warning for an assignment used as a truth value is supported when compiling C++; the other warnings are only supported when compiling C.

Also warn if a comparison like `x<=y<=z' appears; this is equivalent to `(x<=y ? 1 : 0) <= z', which is a different interpretation from that of ordinary mathematical notation. Also warn about constructions where there may be confusion to which if statement an else branch belongs. Here is an example of such a case: { if (a) if (b) foo (); else bar (); } In C, every else branch belongs to the innermost possible if statement, which in this example is if (b). This is often not what the programmer expected, as illustrated in the above example by indentation the programmer chose. When there is the potential for this confusion, GCC will issue a warning when this flag is specified. To eliminate the warning, add explicit braces around the innermost if statement so there is no way the else could belong to the enclosing if. The resulting code would look like this: { if (a) { if (b) foo (); else bar (); } } This warning is enabled by -Wall. -Wsequence-point Warn about code that may have undefined semantics because of violations of sequence point rules in the C standard. The C standard defines the order in which expressions in a C program are evaluated in terms of sequence points, which represent a partial ordering between the execution of parts of the program: those executed before the sequence point, and those executed after it. These occur after the evaluation of a full expression (one which is not part of a larger expression), after the evaluation of the first operand of a &&, ||, ? : or , (comma) operator, before a function is called (but after the evaluation of its arguments and the expression denoting the called function), and in certain other places. Other than as expressed by the sequence point rules, the order of evaluation of subexpressions of an expression is not specified. All these rules describe only a partial order rather than a total order, since, for example, if two functions are called within one expression with no sequence point between them, the order in which the functions are called is not specified. However, the standards committee have ruled that function calls do not overlap. It is not specified when between sequence points modifications to the values of objects take effect. Programs whose behavior depends on this have undefined behavior; the C standard specifies that “Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.”. If a program breaks these rules, the results on any particular implementation are entirely unpredictable. Examples of code with undefined behavior are a = a++;, a[n] = b[n++] and a[i++] = i;. Some more complicated cases are not diagnosed by this option, and it may give an occasional false positive result, but in general it has been found fairly effective at detecting this sort of problem in programs. The present implementation of this option only works for C programs. A future implementation may also work for C++ programs. The C standard is worded confusingly, therefore there is some debate over the precise meaning of the sequence point rules in subtle cases. Links to discussions of the problem, including proposed formal definitions, may be found on the GCC readings page, at http://gcc.gnu.org/readings.html. This warning is enabled by -Wall. -Wreturn-type Warn whenever a function is defined with a return-type that defaults to int. Also warn about any return statement with no return-value in a function whose return-type is not void. For C, also warn if the return type of a function has a type qualifier such as const. Such a type qualifier has no effect, since the value returned by a function is not an lvalue. ISO C prohibits qualified void return types on function definitions, so such return types always receive a warning even without this option. For C++, a function without return type always produces a diagnostic message, even when -Wno-return-type is specified. The only exceptions are `main' and functions defined in system headers. This warning is enabled by -Wall. -Wswitch Warn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration. (The presence of a default label prevents this warning.) case labels outside the enumeration range also provoke warnings when this option is used. This warning is enabled by -Wall. -Wswitch-default Warn whenever a switch statement does not have a default case. -Wswitch-enum Warn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration. case labels outside the enumeration range also provoke warnings when this option is used. -Wtrigraphs Warn if any trigraphs are encountered that might change the meaning of the program (trigraphs within comments are not warned about). This warning is enabled by -Wall. -Wunused-function Warn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is enabled by -Wall. -Wunused-label Warn whenever a label is declared but not used. This warning is enabled by -Wall. To suppress this warning use the `unused' attribute (see Variable Attributes). -Wunused-parameter Warn whenever a function parameter is unused aside from its declaration. To suppress this warning use the `unused' attribute (see Variable Attributes). -Wunused-variable Warn whenever a local variable or non-constant static variable is unused aside from its declaration This warning is enabled by -Wall. To suppress this warning use the `unused' attribute (see Variable Attributes). -Wunused-value Warn whenever a statement computes a result that is explicitly not used. This warning is enabled by -Wall. To suppress this warning cast the expression to `void'. -Wunused All the above -Wunused options combined. In order to get a warning about an unused function parameter, you must either specify `-Wextra -Wunused' (note that `-Wall' implies `-Wunused'), or separately specify -Wunused-parameter. -Wuninitialized Warn if an automatic variable is used without first being initialized or if a variable may be clobbered by a setjmp call. These warnings are possible only in optimizing compilation, because they require data flow information that is computed only when optimizing. If you don't specify -O, you simply won't get these warnings. If you want to warn about code which uses the uninitialized value of the variable in its own initializer, use the -Winit-self option. These warnings occur for individual uninitialized or clobbered elements of structure, union or array variables as well as for variables which are uninitialized or clobbered as a whole. They do not occur for variables or elements declared volatile. Because these warnings depend on optimization, the exact variables or elements for which there are warnings will depend on the precise optimization options and version of GCC used. Note that there may be no warning about a variable that is used only to compute a value that itself is never used, because such computations may be deleted by data flow analysis before the warnings are printed. These warnings are made optional because GCC is not smart enough to see all the reasons why the code might be correct despite appearing to have an error. Here is one example of how this can happen: { int x; switch (y) { case 1: x = 1; break; case 2: x = 4; break; case 3: x = 5; } foo (x); } If the value of y is always 1, 2 or 3, then x is always initialized, but GCC doesn't know this. Here is another common case: { int save_y; if (change_y) save_y = y, y = new_y; ... if (change_y) y = save_y; } This has no bug because save_y is used only if it is set. This option also warns when a non-volatile automatic variable might be changed by a call to longjmp. These warnings as well are possible only in optimizing compilation. The compiler sees only the calls to setjmp. It cannot know where longjmp will be called; in fact, a signal handler could call it at any point in the code. As a result, you may get a warning even when there is in fact no problem because longjmp cannot in fact be called at the place which would cause a problem. Some spurious warnings can be avoided if you declare all the functions you use that never return as noreturn. See Function Attributes. This warning is enabled by -Wall. -Wunknown-pragmas Warn when a #pragma directive is encountered which is not understood by GCC. If this command line option is used, warnings will even be issued for unknown pragmas in system header files. This is not the case if the warnings were only enabled by the -Wall command line option. -Wstrict-aliasing This option is only active when -fstrict-aliasing is active. It warns about code which might break the strict aliasing rules that the compiler is using for optimization. The warning does not catch all cases, but does attempt to catch the more common pitfalls. It is included in -Wall. -Wstrict-aliasing=2 This option is only active when -fstrict-aliasing is active. It warns about code which might break the strict aliasing rules that the compiler is using for optimization. This warning catches more cases than -Wstrict-aliasing, but it will also give a warning for some ambiguous cases that are safe. -Wall All of the above `-W' options combined. This enables all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning), even in conjunction with macros. This also enables some language-specific warnings described in C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. The following -W... options are not implied by -Wall. Some of them warn about constructions that users generally do not consider questionable, but which occasionally you might wish to check for; others warn about constructions that are necessary or hard to avoid in some cases, and there is no simple way to modify the code to suppress the warning. -Wextra (This option used to be called -W. The older name is still supported, but the newer name is more descriptive.) Print extra warning messages for these events: A function can return either with or without a value. (Falling off the end of the function body is considered returning without a value.) For example, this function would evoke such a warning: foo (a) { if (a > 0)
return a;
}

An expression-statement or the left-hand side of a comma expression contains no side effects. To suppress the warning, cast the unused expression to void. For example, an expression such as `x[i,j]’ will cause a warning, but `x[(void)i,j]’ will not.
An unsigned value is compared against zero with `<' or `>=’.
Storage-class specifiers like static are not the first things in a declaration. According to the C Standard, this usage is obsolescent.
If -Wall or -Wunused is also specified, warn about unused arguments.
A comparison between signed and unsigned values could produce an incorrect result when the signed value is converted to unsigned. (But don’t warn if -Wno-sign-compare is also specified.)
An aggregate has an initializer which does not initialize all members. This warning can be independently controlled by -Wmissing-field-initializers.
A function parameter is declared without a type specifier in K&R-style functions:

void foo(bar) { }

An empty body occurs in an `if’ or `else’ statement.
A pointer is compared against integer zero with `<', `<=', `>‘, or `>=’.
A variable might be changed by `longjmp’ or `vfork’.
Any of several floating-point events that often indicate errors, such as overflow, underflow, loss of precision, etc.
(C++ only) An enumerator and a non-enumerator both appear in a conditional expression.
(C++ only) A non-static reference or non-static `const’ member appears in a class without constructors.
(C++ only) Ambiguous virtual bases.
(C++ only) Subscripting an array which has been declared `register’.
(C++ only) Taking the address of a variable which has been declared `register’.
(C++ only) A base class is not initialized in a derived class’ copy constructor.

-Wno-div-by-zero
Do not warn about compile-time integer division by zero. Floating point division by zero is not warned about, as it can be a legitimate way of obtaining infinities and NaNs.
-Wsystem-headers
Print warning messages for constructs found in system header files. Warnings from system headers are normally suppressed, on the assumption that they usually do not indicate real problems and would only make the compiler output harder to read. Using this command line option tells GCC to emit warnings from system headers as if they occurred in user code. However, note that using -Wall in conjunction with this option will not warn about unknown pragmas in system headers—for that, -Wunknown-pragmas must also be used.
-Wfloat-equal
Warn if floating point values are used in equality comparisons.

The idea behind this is that sometimes it is convenient (for the programmer) to consider floating-point values as approximations to infinitely precise real numbers. If you are doing this, then you need to compute (by analyzing the code, or in some other way) the maximum or likely maximum error that the computation introduces, and allow for it when performing comparisons (and when producing output, but that’s a different problem). In particular, instead of testing for equality, you would check to see whether the two values have ranges that overlap; and this is done with the relational operators, so equality comparisons are probably mistaken.
-Wtraditional (C only)
Warn about certain constructs that behave differently in traditional and ISO C. Also warn about ISO C constructs that have no traditional C equivalent, and/or problematic constructs which should be avoided.

Macro parameters that appear within string literals in the macro body. In traditional C macro replacement takes place within string literals, but does not in ISO C.
In traditional C, some preprocessor directives did not exist. Traditional preprocessors would only consider a line to be a directive if the `#’ appeared in column 1 on the line. Therefore -Wtraditional warns about directives that traditional C understands but would ignore because the `#’ does not appear as the first character on the line. It also suggests you hide directives like `#pragma’ not understood by traditional C by indenting them. Some traditional implementations would not recognize `#elif’, so it suggests avoiding it altogether.
A function-like macro that appears without arguments.
The unary plus operator.
The `U’ integer constant suffix, or the `F’ or `L’ floating point constant suffixes. (Traditional C does support the `L’ suffix on integer constants.) Note, these suffixes appear in macros defined in the system headers of most modern systems, e.g. the `_MIN’/`_MAX’ macros in . Use of these macros in user code might normally lead to spurious warnings, however GCC’s integrated preprocessor has enough context to avoid warning in these cases.
A function declared external in one block and then used after the end of the block.
A switch statement has an operand of type long.
A non-static function declaration follows a static one. This construct is not accepted by some traditional C compilers.
The ISO type of an integer constant has a different width or signedness from its traditional type. This warning is only issued if the base of the constant is ten. I.e. hexadecimal or octal values, which typically represent bit patterns, are not warned about.
Usage of ISO string concatenation is detected.
Initialization of automatic aggregates.
Identifier conflicts with labels. Traditional C lacks a separate namespace for labels.
Initialization of unions. If the initializer is zero, the warning is omitted. This is done under the assumption that the zero initializer in user code appears conditioned on e.g. __STDC__ to avoid missing initializer warnings and relies on default initialization to zero in the traditional C case.
Conversions by prototypes between fixed/floating point values and vice versa. The absence of these prototypes when compiling with traditional C would cause serious problems. This is a subset of the possible conversion warnings, for the full set use -Wconversion.
Use of ISO C style function definitions. This warning intentionally is not issued for prototype declarations or variadic functions because these ISO C features will appear in your code when using libiberty’s traditional C compatibility macros, PARAMS and VPARAMS. This warning is also bypassed for nested functions because that feature is already a GCC extension and thus not relevant to traditional C compatibility.

-Wdeclaration-after-statement (C only)
Warn when a declaration is found after a statement in a block. This construct, known from C++, was introduced with ISO C99 and is by default allowed in GCC. It is not supported by ISO C90 and was not supported by GCC versions before GCC 3.0. See Mixed Declarations.
-Wundef
Warn if an undefined identifier is evaluated in an `#if’ directive.
-Wno-endif-labels
Do not warn whenever an `#else’ or an `#endif’ are followed by text.
-Wshadow
Warn whenever a local variable shadows another local variable, parameter or global variable or whenever a built-in function is shadowed.
-Wlarger-than-len
Warn whenever an object of larger than len bytes is defined.
-Wpointer-arith
Warn about anything that depends on the “size of” a function type or of void. GNU C assigns these types a size of 1, for convenience in calculations with void * pointers and pointers to functions.
-Wbad-function-cast (C only)
Warn whenever a function call is cast to a non-matching type. For example, warn if int malloc() is cast to anything *.
-Wcast-qual
Warn whenever a pointer is cast so as to remove a type qualifier from the target type. For example, warn if a const char * is cast to an ordinary char *.
-Wcast-align
Warn whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if a char * is cast to an int * on machines where integers can only be accessed at two- or four-byte boundaries.
-Wwrite-strings
When compiling C, give string constants the type const char[length] so that copying the address of one into a non-const char * pointer will get a warning; when compiling C++, warn about the deprecated conversion from string constants to char *. These warnings will help you find at compile time code that can try to write into a string constant, but only if you have been very careful about using const in declarations and prototypes. Otherwise, it will just be a nuisance; this is why we did not make -Wall request these warnings.
-Wconversion
Warn if a prototype causes a type conversion that is different from what would happen to the same argument in the absence of a prototype. This includes conversions of fixed point to floating and vice versa, and conversions changing the width or signedness of a fixed point argument except when the same as the default promotion.

Also, warn if a negative integer constant expression is implicitly converted to an unsigned type. For example, warn about the assignment x = -1 if x is unsigned. But do not warn about explicit casts like (unsigned) -1.
-Wsign-compare
Warn when a comparison between signed and unsigned values could produce an incorrect result when the signed value is converted to unsigned. This warning is also enabled by -Wextra; to get the other warnings of -Wextra without this warning, use `-Wextra -Wno-sign-compare’.
-Waggregate-return
Warn if any functions that return structures or unions are defined or called. (In languages where you can return an array, this also elicits a warning.)
-Wstrict-prototypes (C only)
Warn if a function is declared or defined without specifying the argument types. (An old-style function definition is permitted without a warning if preceded by a declaration which specifies the argument types.)
-Wold-style-definition (C only)
Warn if an old-style function definition is used. A warning is given even if there is a previous prototype.
-Wmissing-prototypes (C only)
Warn if a global function is defined without a previous prototype declaration. This warning is issued even if the definition itself provides a prototype. The aim is to detect global functions that fail to be declared in header files.
-Wmissing-declarations (C only)
Warn if a global function is defined without a previous declaration. Do so even if the definition itself provides a prototype. Use this option to detect global functions that are not declared in header files.
-Wmissing-field-initializers
Warn if a structure’s initializer has some fields missing. For example, the following code would cause such a warning, because x.h is implicitly zero:

struct s { int f, g, h; };
struct s x = { 3, 4 };

This option does not warn about designated initializers, so the following modification would not trigger a warning:

struct s { int f, g, h; };
struct s x = { .f = 3, .g = 4 };

This warning is included in -Wextra. To get other -Wextra warnings without this one, use `-Wextra -Wno-missing-field-initializers’.
-Wmissing-noreturn
Warn about functions which might be candidates for attribute noreturn. Note these are only possible candidates, not absolute ones. Care should be taken to manually verify functions actually do not ever return before adding the noreturn attribute, otherwise subtle code generation bugs could be introduced. You will not get a warning for main in hosted C environments.
-Wmissing-format-attribute
If -Wformat is enabled, also warn about functions which might be candidates for format attributes. Note these are only possible candidates, not absolute ones. GCC will guess that format attributes might be appropriate for any function that calls a function like vprintf or vscanf, but this might not always be the case, and some functions for which format attributes are appropriate may not be detected. This option has no effect unless -Wformat is enabled (possibly by -Wall).
-Wno-multichar
Do not warn if a multicharacter constant (`’FOOF”) is used. Usually they indicate a typo in the user’s code, as they have implementation-defined values, and should not be used in portable code.
-Wno-deprecated-declarations
Do not warn about uses of functions, variables, and types marked as deprecated by using the deprecated attribute. (see Function Attributes, see Variable Attributes, see Type Attributes.)
-Wpacked
Warn if a structure is given the packed attribute, but the packed attribute has no effect on the layout or size of the structure. Such structures may be mis-aligned for little benefit. For instance, in this code, the variable f.x in struct bar will be misaligned even though struct bar does not itself have the packed attribute:

struct foo {
int x;
char a, b, c, d;
} __attribute__((packed));
struct bar {
char z;
struct foo f;
};

-Wpadded
Warn if padding is included in a structure, either to align an element of the structure or to align the whole structure. Sometimes when this happens it is possible to rearrange the fields of the structure to reduce the padding and so make the structure smaller.
-Wredundant-decls
Warn if anything is declared more than once in the same scope, even in cases where multiple declaration is valid and changes nothing.
-Wnested-externs (C only)
Warn if an extern declaration is encountered within a function.
-Wunreachable-code
Warn if the compiler detects that code will never be executed.

This option is intended to warn when the compiler detects that at least a whole line of source code will never be executed, because some condition is never satisfied or because it is after a procedure that never returns.

It is possible for this option to produce a warning even though there are circumstances under which part of the affected line can be executed, so care should be taken when removing apparently-unreachable code.

For instance, when a function is inlined, a warning may mean that the line is unreachable in only one inlined copy of the function.

This option is not made part of -Wall because in a debugging version of a program there is often substantial code which checks correct functioning of the program and is, hopefully, unreachable because the program does work. Another common use of unreachable code is to provide behavior which is selectable at compile-time.
-Winline
Warn if a function can not be inlined and it was declared as inline. Even with this option, the compiler will not warn about failures to inline functions declared in system headers.

The compiler uses a variety of heuristics to determine whether or not to inline a function. For example, the compiler takes into account the size of the function being inlined and the amount of inlining that has already been done in the current function. Therefore, seemingly insignificant changes in the source program can cause the warnings produced by -Winline to appear or disappear.
-Wno-invalid-offsetof (C++ only)
Suppress warnings from applying the `offsetof’ macro to a non-POD type. According to the 1998 ISO C++ standard, applying `offsetof’ to a non-POD type is undefined. In existing C++ implementations, however, `offsetof’ typically gives meaningful results even when applied to certain kinds of non-POD types. (Such as a simple `struct’ that fails to be a POD type only by virtue of having a constructor.) This flag is for users who are aware that they are writing nonportable code and who have deliberately chosen to ignore the warning about it.

The restrictions on `offsetof’ may be relaxed in a future version of the C++ standard.
-Winvalid-pch
Warn if a precompiled header (see Precompiled Headers) is found in the search path but can’t be used.
-Wlong-long
Warn if `long long’ type is used. This is default. To inhibit the warning messages, use -Wno-long-long. Flags -Wlong-long and -Wno-long-long are taken into account only when -pedantic flag is used.
-Wvariadic-macros
Warn if variadic macros are used in pedantic ISO C90 mode, or the GNU alternate syntax when in pedantic ISO C99 mode. This is default. To inhibit the warning messages, use -Wno-variadic-macros.
-Wdisabled-optimization
Warn if a requested optimization pass is disabled. This warning does not generally indicate that there is anything wrong with your code; it merely indicates that GCC’s optimizers were unable to handle the code effectively. Often, the problem is that your code is too big or too complex; GCC will refuse to optimize programs when the optimization itself is likely to take inordinate amounts of time.
-Wno-pointer-sign
Don’t warn for pointer argument passing or assignment with different signedness. Only useful in the negative form since this warning is enabled by default. This option is only supported for C and Objective-C.
-Werror
Make all warnings into errors.

enable C++ 11 under GNU

enable C++ 11 under GNU
one liner solution : g++ -D__cplusplus=201103L -std=gnu++11

in GUI
This can be set within Eclipse at

  • Add symbol: Project -> Properties -> C/C++ General -> Path and Symbols -> Tab [Symbols]. Add the symbol : __cplusplus with the value 201103L
  • and

  • Set complier flags: Project -> Properties -> C/C++ Build –> setting –> GCC C++ Compiler –> Miscellaneous –> Other flags . add -std=gnu++11

  • why 201103L?

    Read

    #if __cplusplus < 201103L # include
    #else
    ….

    C++11 support
    #end if

    Enable NDK debug on Eclipse , Ubuntu

    Summary

  • Push compiled binary to phone via adb push
    push gdb server to phone
    on phone: run gdb server with given TCP port

    on unbuntu: set TCP port forwarding
    on eclipse: set debug configuration to use TCP connection.

  • Details:

  • Push compiled binary to phone via adb push
    push gdb server to phone
    adb shell push $ANDROID_NDK_ROOT/prebuilt/android-arm/gdbserver/gdbserver /data
    Push compiled binary to phone via adb push

    adb push /home/victor/workspace/xxx/obj/local/armeabi/testPcap /data/app
    on phone: run gdb server with given TCP port
    adb shell
    On phone: /data/gdbserver :5039 /data/app/testPcap

    on unbuntu: set TCP port forwarding 在本地把本地TCP端口forward到设备的TCP端口

    adb forward tcp:5039 tcp:5039

    on eclipse: set debug configuration to use TCP connection.


  • Eclipse 设置调试
    程序为 /home/victor/workspace/xxx/obj/local/armeabi/testPcap
    DEBUGER: gdbserver

    gdb debuger: /home/victor/dev/android-ndk-r9d/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gdb
    gdb commandline: /home/victor/workspace/xxxx/libs/armeabi/droidsheep
    Connection localhost 5039

    TRACE for win32

    // TRACE macro for win32
    #ifndef __TRACE_H__850CE873
    #define __TRACE_H__850CE873
    
    #include <crtdbg.h>
    #include <stdarg.h>
    #include <stdio.h>
    #include <string.h>
    
    #ifdef _DEBUG
    #define TRACEMAXSTRING	1024
    
    char szBuffer[TRACEMAXSTRING];
    inline void TRACE(const char* format,...)
    {
    	va_list args;
    	va_start(args,format);
    	int nBuf;
    	nBuf = _vsnprintf(szBuffer,
    				   TRACEMAXSTRING,
    				   format,
    				   args);
    	va_end(args);
    
    	_RPT0(_CRT_WARN,szBuffer);
    }
    #define TRACEF _snprintf(szBuffer,TRACEMAXSTRING,"%s(%d): ", \
    				&strrchr(__FILE__,'\\')[1],__LINE__); \
    				_RPT0(_CRT_WARN,szBuffer); \
    				TRACE
    #else
    // Remove for release mode
    #define TRACE  ((void)0)
    #define TRACEF ((void)0)
    #endif
    
    #endif // __TRACE_H__850CE873