How To Obtain Network Interface Information In Linux Programmatically
Background
In Linux, usual way to obtain IP Address, Subnet Mask, and Network Address is by calling ifconfig in terminal. From output of this command, we can choose whether we want to manipulate the string before using popen to get the final output or to use string manipulation after getting the raw output by using popen.
Either way, this is not efficient since the output obtained from ifconfig has dependency to format used in providing the information.
Another way to get those information is by utilizing ioctl system call to directly request the information from network device.
Code Implementation
Required headers: string.h, unistd.h, arpa/inet.h, net/if.h, netinet/in.h, sys/ioctl.h, sys/socket.h, sys/types.h.
First we declare variables that we are going to use through this example:
int fd;
struct ifreq ifr;
struct sockaddr_in * adIn=NULL;
struct in_addr inAd;
int status;
Second, we clear ifr, as this is the variable that will be used to get the information from device:
memset(&ifr, 0×0, sizeof(struct ifreq));
Next, create socket as the requirement to provide file descriptor for ioctl:
fd = socket(AF_INET, SOCK_DGRAM, 0);
// if failed then we should not continue
if(fd<0) { return -1; }
Set address family and name of interface that we want to read:
ifr.ifr_addr.sa_family = AF_INET;
// in this example we try to extract information from eth1 interface
strncpy(ifr.ifr_name, “eth1″, IFNAMSIZ-1);
Now let’s first get the IP address:
status=ioctl(fd, SIOCGIFADDR, &ifr);
// if failed then we should not continue
if(status<0) { return -1; }
// get the data and display result
adIn = (struct sockaddr_in *)(&ifr.ifr_addr);
inAd = adIn->sin_addr;
printf(“IP Address: %s\n”, inet_ntoa(inAd));
Next, let’s get the subnet mask:
status=ioctl(fd, SIOCGIFNETMASK, &ifr);
// if failed then we should not continue
if(status<0) { return -1; }
// get the data and display result
adIn = (struct sockaddr_in *)(&ifr.ifr_addr);
inAd = adIn->sin_addr;
printf(“Subnet Mask: %s\n”, inet_ntoa(inAd));
Last, let’s get the network address:
status=ioctl(fd, SIOCGIFBRDADDR, &ifr);
// if failed then we should not continue
if(status<0) { return -1; }
// get the data and display result
adIn = (struct sockaddr_in *)(&ifr.ifr_addr);
inAd = adIn->sin_addr; printf(“Network Address: %s\n”, inet_ntoa(inAd));
Don’t forget to close the file descriptor:
close(fd);
That’s it and hope this helps.
Regards.
Antara Gambir dan Semarang Tawang
Tuesday November 01st 2011, 4:24 PM
Filed under:
Poem
Antara Gambir dan Semarang Tawang,
rindu dan duka bergantian kita bawa.
Ada masa kita menangis, ada masa kita tertawa,
ketika gema denting mulai menari di atas sepur.
Kepada lokomotif kita pasrahkan perjumpaan,
dan kepadanya juga kita pasrahkan perpisahan.
Teriknya Semarang Tawang tak pernah terasa,
saat empat penari menghantarku kepadamu.
Dan Gambir yang kelam mendadak benderang,
saat sinar tajam Sang Argo berkelebat mendekat,
menghantarmu kepadaku.
Atas semua kenangan itu,
aku berterima-kasih kepada Tuhan:
Bahwa di suatu masa,
di ruas-ruas sepur antara Gambir dan Semarang Tawang,
kita pernah saling mencinta.
Jakarta, 1 November 2011
POSIX Basic Regular Expression
Saturday October 29th 2011, 10:37 PM
Filed under:
Programming
Background
Usually when we want to look for certain pattern in a search engine, we use ‘*’ as wildcard to represent part of string that we don’t care if it is there or not as long as it contains pattern that we are looking for. For example search of “*er” may return “toner”, “dinner”, “cooler”, “boxer”, “tumbler”, and any other string with “er” as its two last characters.
Sometimes we find that it is too generic. We may need some more specific wildcards to define pattern of string that contains more than one pattern. For example if we want to get a result of only toner and cooler. This article will explain you how to do it in UNIX environment using POSIX basic regular expression.
List of Wildcards
| Wildcard |
Description |
| * |
Any or no characters. E.g. *t* will match “rate”, “faint”, “toast”, or “ten” |
| . |
Any single character. E.g. .te will only match “ate”, but not “date” |
| [ ] |
Any of characters within the brackets.
‘-’ can be used to represent range. E.g. [a-c] will receive pattern that contains ‘a’, ‘b’, or ‘c’.
Usage combination using ‘-’ as range representation is also accepted. E.g. [a-cx-z] will match ‘a’, ‘b’, ‘c’, ‘x’, ‘y’, or ‘z’.
Note that if ‘-’ is listed as first or last character in the brackets, it will be treated as literal character. E.g. [-a] will match ‘a’ or ‘-’. |
| [^ ] |
Any characters that is not contained within the brackets. E.g. [^a-c] will receive pattern that does not contain ‘a’, ‘b’, or ‘c’. |
| ^ |
Any line beginning with pattern after this wildcard. E.g. ^co will accept “cooler”, “code”, or “coordinate” |
| $ |
Any line ending with pattern before this wildcard. E.g. ^ate will accept “ate”, “fate”, or “workmate” |
| [\ ] |
Escape character. E.g. [\[] will match any line that contains ‘[' character |
Usage Example
If we want to search line containing "apple.seed[0]” or “apple.seed[2]” in files within “src” directory, we can use this command:
grep -rn apple[\.]seed[\[][02][\]] src
Hope this helps.
Regards.
Angan Pada Seutas Tenun
Friday July 01st 2011, 8:41 PM
Filed under:
Poem
Tuhanku,
dalam retas tenun ini,
terpijak angan yang terdalam,
Aku sungguh ingin,
mengajak daun terbang,
menuju Utopia.
Namun Tuhanku,
jika retas ini menjatuhkan,
hingga daun tak pernah tergapai..
Meski dengan berdarah,
aku kan berpasrah:
Terjadilah padaku menurut perkataanMu.
Jakarta, 1 Juli 2011
Aku, kamu, dan lautan luas
Tuesday May 31st 2011, 2:12 AM
Filed under:
Poem
Aku tak mau peduli,
kemana arus sungai ini akan membawa kita.
Selama kamu di sini,
mendayung bersamaku.
Aku yakin suatu hari nanti,
ketika matahari mulai terbit,
dan kepakan burung camar mulai terdengar,
lautan luas akan menghampar.
Sambil menghirup aroma amis laut yang khas,
kita akan bermain,
bersama anjing laut dan lumba-lumba,
hingga malam tiba,
dan kita terlarut di tengah lautan,
menuju hidup abadi,
di mana cinta adalah zat yang kita hirup dan kita hembuskan.
Jakarta, 31 Mei 2011.
Variable Length Subnet Masking
Saturday May 14th 2011, 11:41 PM
Filed under:
Networking
Main Concept
Variable Length Subnet Masking (VLSM) is a method to allocate Internet Protocol (IP) addresses based on requested number of subnet and requested hosts of each subnet. Each subnet will have dynamic number of hosts, which will minimize number of unused hosts.
Case Example
Given IP Address of B Class: 128.128.32.0/20
Requested hosts and subnets:
- 2 subnets @ 200 hosts
- 1 subnet @ 50 hosts
- 3 subnets @ 100 hosts
Define subnet mask and IP addresses allocation for each subnet!
Solution
Step 1: Sort subnet from the most requiring number of hosts.
By naming two subnets with 200 hosts each as A1 and A2, one subnet with 50 hosts as C1 and the rest four as B1, B2, and B3, we can create following table:
| Subnet Name |
Number of Hosts |
Host’s Bit Range |
Usable Hosts |
| A1 |
200 |
8 |
254 |
| A2 |
200 |
8 |
254 |
| B1 |
100 |
7 |
126 |
| B2 |
100 |
7 |
126 |
| B3 |
100 |
7 |
126 |
| C1 |
50 |
6 |
62 |
Note:
- host’s bit range can be determined using this formula:
2n >= r
where n is the bit range and r is number of requested hosts.
- usable hosts can be determined using this formula:
u = 2n-2
where u is usable hosts and n is host’s bit range
Step 2: Determine subnet masks.
Subnet mask can be determined using n we got in first step.
n tells how many bits having to be set to 0 from right.
| Subnet Name |
Host’s Bit Range |
Subnet Mask |
| A1 |
8 |
11111111.11111111.11111111.00000000 = 255.255.255.0 |
| A2 |
8 |
11111111.11111111.11111111.00000000 = 255.255.255.0 |
| B1 |
7 |
11111111.11111111.11111111.10000000 = 255.255.255.128 |
| B2 |
7 |
11111111.11111111.11111111.10000000 = 255.255.255.128 |
| B3 |
7 |
11111111.11111111.11111111.10000000 = 255.255.255.128 |
| C1 |
6 |
11111111.11111111.11111111.11000000 = 255.255.255.192 |
Step 3: Allocate IP address for each subnet.
We start from the requested IP and add them respective to the order with 2n.
Subnet A1:
Network address: 128.128.32.0
Broadcast address: 128.128.32.255
Host range: 128.128.32.1 - 128.128.32.254
Subnet A2:
Network address: 128.128.33.0
Broadcast address: 128.128.33.255
Host range: 128.128.33.1 - 128.128.33.254
Subnet B1:
Network address: 128.128.34.0
Broadcast address: 128.128.34.127
Host range: 128.128.34.1 - 128.128.34.126
Subnet B2:
Network address: 128.128.34.128
Broadcast address: 128.128.34.255
Host range: 128.128.34.129 - 128.128.34.254
Subnet B3:
Network address: 128.128.35.0
Broadcast address: 128.128.35.127
Host range: 128.128.35.1 - 128.128.35.126
Subnet C1:
Network address: 128.128.35.128
Broadcast address: 128.128.35.191
Host range: 128.128.35.129 - 128.128.35.190
Remarks
VLSM can be considered as FLSM successor because it offers more efficient way in allocating IP Address.
Silver Age
Saturday April 30th 2011, 6:28 PM
Filed under:
Personal
April Surprise
I don’t exactly remember what happened at the first ticks of my 25th age. All I can recall is that evening where I was in a car with my dad taking me to the restaurant where we’re gonna have a little party to celebrate my silver age. A party with my dad, mom, my little brother, and my paternal grand-parents.
Then there I was sitting at the table with my brother, my dad, and my grandparents, where to my surprise, Monica came with her family. I did not know she would come - as what I knew was she was in Bandung with her family and would come to Jakarta some days after my birthday. Monica was half of my heart, she was the only I wanted to love, the only that I wanted..
We got a great night after the party although we failed to watch movie, we spent our night sharing the moment we should normally have. We were in a long distance relationship, so every time we met, we never wanted to let the clock ticking
Even after dropped by my parents at Djarum mess where she stayed with her family during their time at Jakarta, we didn’t want to sleep, we wanted to keep on talking, but our eyes were screaming, asking for a rest. Knowing we could not fight it, we decided to sleep. She went to her room, and I went to room where her brother was sleeping. She slept with her sister. Before sleeping, I replied all happy birthday messages in Facebook from my great friends using my Nokia 6120 classic.
God’s presents
God never stops sending gifts every time I have a birthday. I don’t remember all of them, though.
That year He gave me something very special. I got a promotion with significant salary increment by end of April and a business trip to Kuala Lumpur, Malaysia. I went there with my senior to update AMDS in 6 (six) AirAsia’s airbuses. Two of them were A-340, while the rest were A-330. That was the first time I went to Malaysia. Malaysia was great, I loved being there. The food was not different significantly than in Jakarta. I loved Nasi Briyanni and Nestle ice cream that I bought from a small store at LCCT Food Court. The hotel accommodated was also nice. It had swimming pool and greatest breakfast ever in life. Since the job provided a lot of spare times, we managed to travel to the city also.
Again, I was assigned to KL at beginning of June. Although that trip sent me home with illness at spine, I never stopped wanting to return and doing things like what I have done again.
World Cup 2010
June and July of 2010 are months where mind of world’s population were directed to South Africa. I was happy that I spent this World Cup with the only girl that I loved. We watched some of early matches in Jogjakarta while also curing my spine at Panti Rapih Hospital, nearby the University of Gajah Mada. We also celebrated her birthday which was also our 2nd anniversary in a seafood restaurant in Tanah Mas, Semarang with her family.
Although I was in a hectic, I managed to escape to Salatiga to spend final moments of World Cup in Salatiga with her. We watched the final at Laras Asri Hotel where Spain beat Holland 1-0, thanks to Andrés Iniesta’s 117th minute strike.
July was also the month where she was going to be graduated. My family were also going to her university to celebrate her graduation along with her family.
I can’t remember any other thing as much as delicious Cobra Ice we enjoyed after the ceremony.
The Break-up
I was so happy hearing that she finally got a job in Jakarta, meaning we could have a normal relationship like most couples had, meeting everyday, and watching movie every weekend.
But bizarre feeling also came along..
I don’t know and remember precisely how that feeling came to my mind. To be honest, I didn’t feel as comfortable as we had been, and I started to see the future of this relationship in doubt. She was different, something had changed, I realized I was different also. But I tried to pretend that everything was okay because my love for her still remained the same.
Shortly, after going back to Jakarta from her sister’s engagement in Pati, we did not talk as much as we had done anymore. We didn’t talk for three days to be exact. And after sometimes, at November 1st, 2010, we decided to not try retaining our relationship anymore. We cried like crazy that night, and again, the feeling of losing half of my heart came again. But I believed, that was actually how our path had been drawn by God. It was the end point where we should continue our journey not as a couple again. We should continue walking in two separate ways.
“Bahkan ketika jalan takdir kita harus terpisah, cinta ku pada mu takkan pernah padam..”
And yes, up until now, I know it still burns.
Magister Study
I started continuing my study in Computer Science at second week of November. This month, I was sent to Singapore again to initiate research about drawing using Open GL ES 2.0 in Fujitsu Ruby GPU.
My study is very helpful in terms of diverting my mind away from the break-up. I get more and more hectic as many assignments are given by lecturers while GeoDesktop is also in need of a total revamp to support AMDS/B.
That’s very helpful for my mind, but not for my body, I never feel as fresh as I was before.
Fernando Torres’ move
January saw Fernando Torres, a player that Liverpool FC fans would die for, moved to arch-rival, Chelsea FC in exchange of reportedly 50 million Poundsterling. Fernando himself asking for this transfer. This transfer also hurt me, and I hoped the worst in his endeavor with Chelsea. I once also wished he would not score until I had my age incremented.
The nightmare for him started at his debut where Chelsea FC were beaten 0-1 at Stamford Bridge, thanks to Raul Meireles’ goal. This match also saw Daniel Agger hit his elbow to foul Fernando Torres at left flank of Liverpool defense. Agger, hence, be the first player who fouled Fernando since his move away from Liverpool.
The accidents
I finally biked my new motorcycle at the beginning of April 2011, but I don’t know why I made a hat-trick of accidents in less than a week. Twice at 6th of April and the worst at 12th while I was about to recover from the first one. I was absent from study for nearly a week and from work for nearly two weeks.
Ticks before my 26
I hope those accidents would bring me much better luck for my upcoming 26th age in exchange. Last two football matches I watched in my 25 were Liverpool FC vs Birmingham City and Brescia vs AC Milan. Maxi Rodriguez scored hat-trick in Liverpool’s comfortable 5-0 victory and Robinho brought Milan eight points clear from Internazionale in Serie A after scoring the only goal in Stadio Mario Rigamonti, thanks to clever assist by Antonio Cassano.
Right 15 minutes before my birthday, Fernando Torres scored his first goal for Chelsea FC in rainy field of Stamford Bridge in London derby against Westham United. Although it happened before my birthday, I smiled, looking back that it took fourteen matches for him to score his first goal for Chelsea
So, here I am a week after, ready or not, I am 26 now
Fixed Length Subnet Masking
Thursday April 28th 2011, 1:26 PM
Filed under:
Networking
Main Concept
Fixed Length Subnet Masking (FLSM) is a method to allocate Internet Protocol (IP) addresses based on requested number of subnet. Every subnets will have fixed number of IP addresses allocated, regardless they are used entirely or not.
Case Example
Given IP Address of C Class: 192.45.100.0/24
Requested subnets: 4
Define subnet mask and IP addresses allocation for each subnet!
Solution
Step 1: Determine bit range of each subnet.
Bit range of each subnet can be determined using this formula:
2n >= r
where n is the bit range and r is number of requested subnet.
Since r in this case equals to 4, the bit range can be determined as 2.
Step 2: Determine subnet mask.
Subnet mask can be determined using n we got in first step.
Since n equals to 2, two most significant bits in last octet should be set as 1 while the rest are set to 0.
Therefore, the subnet mask can be determined as 255.255.255.[11000000] = 255.255.255.192
Step 3: Allocate IP addresses for each subnet.
Set last octet to be 00000000 for network address.
Set last octet to be 11111111 for broadcast address.
Add first n (from the first step) most significant bits one by one for every new subnet until all n bits turned into 1.
Using case example, we will use two most significant bits to determine IP address range of every subnet requested.
Subnet-0:
Network address: 192.45.100.[00000000] = 192.45.100.0
Broadcast address: 192.45.100.[00111111] = 192.45.100.63
Host range: 192.45.100.1 - 192.45.100.62
Subnet-1:
Network address: 192.45.100.[01000000] = 192.45.100.64
Broadcast address: 192.45.100.[01111111] = 192.45.100.127
Host range: 192.45.100.65 - 192.45.100.126
Subnet-2:
Network address: 192.45.100.[10000000] = 192.45.100.128
Broadcast address: 192.45.100.[10111111] = 192.45.100.191
Host range: 192.45.100.129 - 192.45.100.190
Subnet-3:
Network address: 192.45.100.[11000000] = 192.45.100.192
Broadcast address: 192.45.100.[11111111] = 192.45.100.255
Host range: 192.45.100.193 - 192.45.100.254
Remarks
FLSM has however now been obsolete and used rarely since introduction to a more reliable and efficient way to determine IP address with varying range for each subnet. This new method is called Variable Length Subnet Masking (VLSM).
Uruguay trashed Indonesia 7-1
Saturday October 09th 2010, 11:02 PM
Filed under:
Soccer

Watched by Indonesia President, Susilo Bambang Yudhoyono, Indonesia didn’t turn any prediction and suffered a heavy defeat to World Cup 2010 semi-finalist, Uruguay at Gelora Bung Karno Stadium, Jakarta.
Indonesia surprisingly opened the score from Boas Solossa after controlling the left foot chip from captain Bambang Pamungkas. He rounded Juan Castillo and comfortably slotted the ball to the empty net in 17th minute.
However, Uruguay did not take too long to peg back as Edinson Cavani headed strongly a cross from Jorge Fucile from the left side of Indonesia defence 18 minutes later.
Luis Suarez brought Uruguay ahead with his goal after overcoming two Indonesia defenders three minutes before break.
Eight minutes after break, Suarez again found the net after winning one-on-one situation with Indonesia goalkeeper, Markus Horison.
Sebastian Eguren increased the edge as he scored on 58th minute after an excellent team work display with Suarez.
On 69th minute, Suarez completed his hattrick after scoring from the spot following Horison’s foul to Cavani.
Cavani himself later also completed his hattrick by scoring two another goals in last ten minutes.
Starting Line-ups
Indonesia:
1-Markus Horison; 6-Nova Arianto; 5-Maman Abdurahman; 8-Toni Sucipto; 5-Firman Utina (Oktovianus Maniani); 11-Boaz Solossa; 2-M. Ridwan; 16-Beny Wahyudi; 19-Ahmad Bustomi; 13-M. Nasuha (Slamet Riyadi); 20-Bambang Pamungkas (c) (Yongki Aribowo)
Uruguay:
12-Juan Guillermo Castillo; 4-Jorge Fucile (Ramirez); 2-Diego Lugano (c) (Andres Scotti); 16-Maximiliano Pereira; 6-Mauricio Victorino (Martin Caceres); 11-Alvaro Pereira; 7-Cristian Rodriguez; 15-Diego Perez (Sebastian Eguren); 5-Walter Gargano; 9-Luis Suarez; 10-Edinson Cavani
Referee:
Abbas bin Daud
Image source: 1
Berba scores hattrick as victorious United escape from close encounter
Sunday September 19th 2010, 11:38 PM
Filed under:
Soccer

A header from Dimitar Berbatov six minutes before time had restored Manchester United’s lead and thus ensured the team to gain victory in tonight’s super clash between Manchester United and Liverpool FC at Old Trafford Stadium, Manchester.
The Bulgarian scored his first from corner kick taken by Ryan Giggs four minutes before half time. The perfectly delivered ball was headed to the net after he escaped from imperfect marking from Fernando Torres. The ball was slightly tipped by Liverpool’s newly-signed defender, Paul Konchesky, before going into the goal.
Konchesky himself played a bit disappointing tonight despite of his excellent determination in first 7 minutes of the game by scrambling away a cross delivered by Patrice Evra to Berbatov in the 6 yard box and blocking Nani’s attempt from left deep.
Berbatov’s second goal was absolutely a contender for goal of this season. Controlling the ball crossed by Nani with his thigh, Berbatov did an awesome overhead kick that stunned José Manuel Reina.
A through pass from Joe Cole into the box almost freed Torres from his marker, but Jonathan Evans fouled Torres, having himself booked and also giving a chance for Liverpool to score from the spot. Steven Gerrard did well to give Liverpool a glimpse of hope on 62nd minute.
Liverpool equalised after Steven Gerrard scored from direct free kick following foul committed by John O’Shea to Fernando Torres on 69th minute. It should have been a sending-off as Torres was in a very advantageous position to score a goal, but O’Shea escaped luckily as he only received a yellow card.
Another yellow card had been issued for Wayne Rooney after a foul against Torres on 57th minute. This incident happened right after Nani had hit the left of Reina’s post.
Starting Line-ups
Manchester United FC:
1-Edwin van der Saar; 22-John O’ Shea; 15-Nemanja Vidić (c); 23-Jonathan Evans; 3-Patrice Evra; 24-Darren Fletcher; 18-Paul Scholes; 17-Nani (28-Darron Gibson 88′); 11-Ryan Giggs (27-Federico Macheda 82′); 9-Dimitar Berbatov (8-Anderson 88′); 10-Wayne Rooney
Liverpool FC:
1-José Reina; 2-Glen Johnson; 23-Jamie Carragher; 37-Martin Škrtel; 3-Paul Konchesky (5-Daniel Agger 82′); 4-Raúl Meireles (14-Milan Jovanović 79′); 28-Christian Poulsen; 17-Maxi Rodríguez (24-David N’Gog 62′); 8-Steven Gerrard (c); 10-Joe Cole; 9-Fernando Torres
Referee:
Howard Webb
Image source: 1