Ady Wicaksono Daily Activities

Archive for the ‘C/C++’ Category

Detecting MAC Address using C application

with 10 comments

I got this code long time ago from somewhere (off course from internet), using this C code it’s now simpler for you to create application that needs to detect MAC address.

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

#ifdef Linux
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <linux/if.h>
#endif

#ifdef HPUX
#include <netio.h>
#endif

#ifdef AIX
#include <sys/ndd_var.h>
#include <sys/kinfo.h>
#endif

long mac_addr_sys ( u_char *addr)
{
/* implementation for Linux */
#ifdef Linux
    struct ifreq ifr;
    struct ifreq *IFR;
    struct ifconf ifc;
    char buf[1024];
    int s, i;
    int ok = 0;

    s = socket(AF_INET, SOCK_DGRAM, 0);
    if (s==-1) {
        return -1;
    }

    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = buf;
    ioctl(s, SIOCGIFCONF, &ifc);

    IFR = ifc.ifc_req;
    for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++) {

        strcpy(ifr.ifr_name, IFR->ifr_name);
        if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) {
            if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
                if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0) {
                    ok = 1;
                    break;
                }
            }
        }
    }

    close(s);
    if (ok) {
        bcopy( ifr.ifr_hwaddr.sa_data, addr, 6);
    }
    else {
        return -1;
    }
    return 0;
#endif

/* implementation for HP-UX */
#ifdef HPUX

#define LAN_DEV0 "/dev/lan0"

    intfd;
    struct fisiocnt_block;
    inti;
    charnet_buf[sizeof(LAN_DEV0)+1];
    char*p;

    (void)sprintf(net_buf, "%s", LAN_DEV0);
    p = net_buf + strlen(net_buf) - 1;

    /*
     * Get 802.3 address from card by opening the driver and interrogating it.
     */
    for (i = 0; i < 10; i++, (*p)++) {
        if ((fd = open (net_buf, O_RDONLY)) != -1) {
iocnt_block.reqtype = LOCAL_ADDRESS;
ioctl (fd, NETSTAT, &iocnt_block);
close (fd);

            if (iocnt_block.vtype == 6)
                break;
        }
    }

    if (fd == -1 || iocnt_block.vtype != 6) {
        return -1;
    }

bcopy( &iocnt_block.value.s[0], addr, 6);
return 0;

#endif /* HPUX */

/* implementation for AIX */
#ifdef AIX

    int size;
    struct kinfo_ndd *nddp;

    size = getkerninfo(KINFO_NDD, 0, 0, 0);
    if (size <= 0) {
        return -1;
    }
    nddp = (struct kinfo_ndd *)malloc(size);
        
    if (!nddp) {
        return -1;
    }
    if (getkerninfo(KINFO_NDD, nddp, &size, 0) < 0) {
        free(nddp);
        return -1;
    }
    bcopy(nddp->ndd_addr, addr, 6);
    free(nddp);
    return 0;
#endif

/* Not implemented platforms */
return -1;
}

/***********************************************************************/
/*
 * Main (only for testing)
 */
#ifdef MAIN
int main( int argc, char **argv)
{
    long stat;
    int i;
    u_char addr[6];

    stat = mac_addr_sys( addr);
    if (0 == stat) {
        printf( "MAC address = ");
        for (i=0; i<6; ++i) {
            printf("%2.2x", addr[i]);
        }
        printf( "\n");
    }
    else {
        fprintf( stderr, "can't get MAC address\n");
        exit( 1);
    }
    return 0;
}
#endif

E.g you want to use on Linux, save it as file.c simply compile like this:

   gcc -O2 -DMAIN -DLinux file.c -o file

And run it

./file
MAC address = 0008c7e9e386

Compare with /sbin/ifconfig result:

/sbin/ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 00:08:C7:E9:E3:86
          inet addr:***.***.***.***  Bcast:***.***.***.***  Mask:255.255.255.0
          inet6 addr: ********************* Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:265555947 errors:0 dropped:0 overruns:0 frame:0
          TX packets:50507373 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:4090310752 (3.8 GiB)  TX bytes:1085018636 (1.0 GiB)

It’s the same 🙂

Advertisements

Written by adywicaksono

November 8, 2007 at 9:29 am

Posted in C/C++, Linux

Patch Kannel to disable enquire_link/enquire_link_resp logging

leave a comment »

Kannel monitoring sometimes needed by administrator. Normally, we will activate debug log to monitor submit_sm, deliver_sm, data_sm, and similar one. But, maybe you got annoyed by enquire_link & enquire_link_resp which normally done almost every 30 seconds or less.

To enable debug mode of kannel but skip enquire_link/resp you need to modify

1. gw/smsc/smpp_pdu.c

Find function name “void smpp_pdu_dump(SMPP_PDU *pdu)” and add this line at the
on the first line of function body code:

// No need enquire_link debug info
if(pdu->type == 0x80000015){
   return;
}

2. gw/smsc/smsc_smpp.c
Find function name “static void send_enquire_link(SMPP *smpp, Connection *conn, long *last_sent)” and add remove or comment this line.

dump_pdu("Sending enquire link:", smpp->conn->id, pdu);

3. gw/smsc/smsc_smpp.c
Find function name “static void io_thread(void *arg)” and find this line

/* Deal with the PDU we just got */
dump_pdu("Got PDU:", smpp->conn->id, pdu);

Change to

Written by adywicaksono

October 11, 2007 at 4:23 pm

Posted in C/C++, kannel

Learning C/C++ part 1

with 7 comments


#include <iostream>
#include <cstdlib> // Define system()
#include <string>  // Define string
#include <fstream> // File Operation
#include <vector>  // The same with java Vector implementation
using namespace std;

// Global Variable
int globalIntOK = 1000;

string hello(){
    return "Hello TAHU\n";
}

void swap(int *a, int *b){
    int c;
    c  = *a; // C now contains memory address of a
    *a = *b; // data pointed by address memory a is now contain data pointed by memory b
    *b = c;  // data pointed by address memory b is now = c
}

void func_withnostatic(){
    int y = 10;
    cout << "y: " << y++ << endl;
}

void func_withstatic(){
    static int y = 10;
    cout << "y: " << y++ << endl;
}

void swapCPP(int& a, int& b){
    cout << "C++ SWAP -> a = " << a << endl;
    cout << "C++ SWAP -> b = " << b << endl;
    cout << "C++ SWAP address -> a = " << &a << endl;
    cout << "C++ SWAP address -> b = " << &b << endl;

    int c;
    c = a; // karena &a adalah alamat memory,
    // maka a adalah isi dari alamat memori itu
    a = b;
    b = c;
}

int main_learn1(int argc, char **argv){
    int number;
    cout << "Hello World" << endl
    << "Hello too !" << endl;
    cout << "Number 15 in decimal: " << dec << 15 << endl;
    cout << "Number 15 in octal : " << oct << 15 << endl;
    cout << "Number 15 in hex : " << hex << 15 << endl;
    cout << "Floating Point : " << 15.12 << endl;
    cout << "Char(27) is : " << char(27) << endl;
    cout << "Char concat "
    " continue 1 "
    " continue 2 " << endl;
    cout << "Enter Number: " ;
    cin >> number;
    cout << "Number: " << dec << number << endl;

    // Calling SYSTEM Program
    system("echo 'Hallo ADY'");

    // String on C++
    string s1, s2; // Empty String
    string s3 = "hello World String"; // init string
    string s4("Hello World Another string"); // init string too

    cout << "String 3: " << s3 << endl;
    cout << "String 4: " << s4 << endl;

    cout << "Just like java...concat is simple-> " << s3 + " " + s4 << endl;

    s1 = "testaja.yt";
    ifstream inFile(s1.c_str()); // ifstream -> open for reading
    if(inFile.is_open()){
        cout << "File " << s1 << " is opened" << endl;
        string buff1;
        while(getline(inFile,buff1)){ // ReadFile .. but '\n' discarded
            cout << buff1 << endl;
        }
        inFile.close();
    }else{
        cout << "File " << s1 << " is NOT opened" << endl;
    }

    ofstream outFile(s1.c_str()); // ofstream -> open for writing
    if(outFile.is_open()){
        cout << "File " << s1 << " is opened to be written" << endl;
        outFile.write(s3.c_str(),s3.length());
        outFile.close(); // Close File
    }else{
        cout << "File " << s1 << " is NOT opened to be written" << endl;
    }

    cout << "Vector" << endl;
    string x1,x2,x3;
    vector<string> vStr;

    x1 = "Data 1";
    x2 = "Data 2";
    x3 = "Data 3";
    vStr.push_back(x1); // Masukin Elemen
    vStr.push_back(x2); // Masukin Elemen
    vStr.push_back(x3); // Masukin Elemen

    // Tampilkan Elemen
    int i;
    for(i=0; i < vStr.size(); i++){
        cout << "Elemen ke-" << i+i << ": " << vStr[i] << endl;
    }

    vector<int> vInt;
    vInt.push_back(1);
    vInt.push_back(2);
    vInt.push_back(3);
    for(i=0; i < vInt.size(); i++){
        cout << "Elemen ke-" << i+i << ": " << vInt[i] << endl;
    }

    // Fungsi juga bisa dipakai lho untuk cout
    cout << "Hasil fungsi hello(): " << hello() << endl;

    // Ada boolean di sana
    bool x;
    x = true;

    cout << "Boolean x = " << x << endl;

    // Pointer tetap ada
    int y = 1231;
    cout << "Alamat memory dari y yang bernilai " << y << ", adalah " << (long)&y << endl;
    cout << "Alamat memory dari fungsi hello(), adalah " << (long)&hello << endl;

    int abc = 1000;
    int *p_abc = &abc; // p_abc adalah pointer ke integer -> diacu ke alamat abc
    cout << "ABC = " << abc << endl;
    *p_abc = 2000;
    cout << "Skrg ABC = " << abc << endl;

    // Fungsi Pointer dengan C

    char ans;
    while(true){
        cout << "Ketik y untuk melanjutkan: ";
        cin >> ans;
        if(ans == 'y'){
            break;
        }
    }
    int tahu = 100;
    int tempe = 200;
    cout << "Tahu = " << tahu << endl;
    cout << "Tempe = " << tempe << endl;
    swap(&tahu,&tempe); // Alamat memory tahu & tempe dipass ke fungsi
    cout << "SWAP(), now...\nTahu = " << tahu << endl;
    cout << "Tempe = " << tempe << endl;

    // C++ reference
    // C++ punya model baru untuk pass by reference,
    // Yakni dengan menggunakan tanda & pada parameter fungsi, bukan *
    swapCPP(tahu,tempe);
    cout << "SWAP back with C++ Reference(), now...\nTahu = " << tahu << endl;
    cout << "Tempe = " << tempe << endl;

    cout << "Now about scoping" << endl;
    { int tahutempe; // variabel ini hanya dikenali di sini
    };

    // Disini jika diuncomment akan tampil
    // : error C2065: 'tahutempe' : undeclared identifier (vc++6)
    /* cout << "Tahu Tempe variabel? " << tahutempe; */

    // Global Variable
    cout << "Global Variable globalIntOK = " << globalIntOK << endl;

    // Register Variable, process it as fast as you can :D
    // Only valid in block, you may not have global register :D
    register int test01 = 1001;
    cout << "Test01 Var as Register = " << test01 << endl;

    // Static Variables
    // Variabel yang tidak didefinisikan static dalam sebuah fungsi
    // nilainya akan diinisialisasi ulang, tp jika static maka
    // saat "return" dari fungsi nilainya akan tetap disimpan
    // Static mirip dengan global, tapi variabel static hanya berlaku
    // dalam blok fungsi dimana dia diterapkan :)
    // dikenal juga file scope, dimana static variabel yang ditaruh
    // spt penempatan variabel global -> berarti variabel ini hanya dikenali
    // di file ini saja
    for(i = 0; i < 10; i++){
        func_withnostatic();
    }
    for(i = 0; i < 10; i++){
        func_withstatic();
    }

    // Variabel extern ... waktu dilakukan linking (compile -> link)
    // diasumsikan ada diantara file2 yang linking
    /*
    When the compiler encounters the declaration ‘extern int i’, it
    knows that the definition for i must exist somewhere as a global
    variable.
    */
    // Constanta di C++
    // di C biasanya digunakan macro
    #define MY_CONST 1000
    cout << "My Const = " << MY_CONST << endl;
    // di C++ bisa digunakan const
    const int h = 121;
    cout << "Const h = " << h << endl;

    return 0;
}

int main_learn2(int argc, char **argv){
    return 0;
}

int main(int argc, char **argv){
    main_learn1(argc,argv);
    return 0;
}

Written by adywicaksono

October 5, 2007 at 10:19 pm

Posted in C/C++