Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Monday, May 09, 2016

Using POSIX time related functions shows PTP time

One major different: The PTP time counts from 1990. POSIX function count from 1970.

The POSIX struct tm is
int tm_year
int tm_month
int tm_day
int tm_min
int tm_sec

Because I do not find function, I create the easy one to fill tm_xxx below.

/*
Copyright (C) 2016 YKLin

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

typedef struct _TIMESTAMP_S{
    uint16        epoch_number;
    uint32        seconds;
    uint32        nanoseconds;
} timestamp_t;
void _converttime(struct tm *mytime, uint64 epoch){
    int years=0, months=0,days=0,hours=0,minutes=0;
    if(!mytime){
        return;
    }
    if(epoch >= 31556926UL){
        years = epoch/31556926UL;
        epoch -= years*31556926UL;
    }
    if(epoch >= 2629743UL){
        months = epoch/2629743UL;
        epoch -= months*2629743UL;
    }
    if(epoch >= 86400UL){
        days = epoch/86400UL;
        epoch -= days*86400UL;
    }
    if(epoch >= 3600UL){
        hours = epoch/3600UL;
        epoch -= hours*3600UL;
    }
    if(epoch >= 60){
        minutes = epoch/60;
        epoch -= minutes*60;
    }
    mytime->tm_sec = (int)epoch;
    mytime->tm_year += years;
    mytime->tm_mon += months;
    mytime->tm_mday += days;
    mytime->tm_hour += hours;
    mytime->tm_min += minutes;
}
int _convertTimestapTotm(struct tm *mytime, timestamp_t *ts){
    if(!mytime || !ts){
        return FAILED;
    }
   _converttime(mytime, (uint64)ts->epoch_number<<32);
   _converttime(mytime, (uint64)ts->seconds);
    _converttime(mytime, (uint64)0x83aa7e80);
    return SUCCESS;
}

Thursday, April 28, 2016

Modify binary file

It's been a while not writing anything because the my career changing to verify IC.
However, there is the little python script for modifying binary file byte by byte. The following code opens a file and seek to offset 0xAFF7 at the beginning. It writes 0xCC, 0xE2, 0x54, 0x7a into file.

import struct
magic = (0xCCE2, 0x547A)
with open("binary.bin", "r+b") as f:
    f.seek(0xAFF7)
    for m in magic:
        f.write(struct.pack('h', m))
    f.close()


Sunday, January 09, 2011

select function does not stop

I use named FIFO and select function to do IPC programming. When program execute to "if(select(myfd+d, myfdSet, NULL, NULL, &waittime) > 0 && IS_SET(myfdSet))", it always fulfill condition even there is no any process wrote into named FIFO.
After I examin again, I find out that I open file as "O_RDONLY". Refer to Linux's man page, there is a section to discript it:


Under Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks.

Hence, I modify open statement from myfd = open("/tmp/a", O_RDONLY) to myfd = open("/tmp/a", O_RDWR|O_NONBLOCK). Everything is perfect right.

Saturday, May 22, 2010

Convert Multicast IPv4 Address to MAC address

There is a mapping between Multicast IP address and MAC address. The first three bytes of Multicast MAC address are always 01:00:5e, the last three bytes are filled from Multicast IP-form.
We drop the highest nine bits of IP address and convert to MAC address. And this number will become Multicast MAC address.

For example, IP: 224.10.10.10 , its decimal is 375875314. After we drop the highest nine bits, it becomes 657930. So, the Multicast MAC address is: 01:00:5e:0a:0a:0a. Here is a example C source code (GPL) to show this:

/*
Copyright (C) 2010 YKLin

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void cvtIP2MAC(unsigned long, unsigned char*);

int main(int argc, char **argv){
char ipaddress[255]="224.10.0.1";
unsigned char buf[6] = {0x01, 0x0, 0x5e, 0x0, 0x0, 0x0};
struct in_addr inputAddress;
int ret;
memset(&inputAddress, 0x0, sizeof(inputAddress));
if(argc > 1){
strcpy(ipaddress, argv[1]);
}

ret = inet_aton(ipaddress, &inputAddress);
if(!ret){
printf("Dest address(%s) is incorrect:%d\r\n", ipaddress, ret);
return -1;
}
printf("Conver IP(%s, %u) to MAC...\r\n", ipaddress, ntohl(inputAddress.s_addr));
MIPv42MAC(ntohl(inputAddress.s_addr), buf);
printf("MAC: %02x %02x %02x %02x %02x %02x\r\n", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);
return 0;
}
void cvtIP2MAC(unsigned long ip, unsigned char *buf){
if(!buf){
return;
}
buf[5] = ip & 0xff;
buf[4] = (ip & 0xff00)>>8;
buf[3] = (ip & 0xff0000)>>16;

}

Friday, January 15, 2010

A coding convention of JAVA

I read a post about how to wirte JAVA in java-style. Here is a interesting item:

Use s == null, not null == s

It's true that I use null == s when I write c programming and it is really useful. The author explained why JAVA does not use null == s. In JAVA world, it will cause compile error when using statements below:
if( iNum = do_some_check()) {do_some_thing(iNum);} /*............Statement 1*/

We should use in JAVA world:
iNum = do_some_check();
if(iNum!=0){do_some_thing(iNum);} /*............Statement 2*/

C programmers often use Statement 1 to save semantics, because it is totally legal to use "assign operater in "if" statement in C's world. If C programmer is "too tired", she/he will write incorrect semantic statement below to check iNum is equal to 99:
if(iNum = 99){do_some_thing(iNum)};/*............Statement 3*/

Hence, there is a common sense to check iNum is equal to 99 like this:
if( 99 == iNum){do_some_thing(iNum)};/*............Statement 4*/

However, we are free to this kind of fear in JAVA's world. We do not have to write JAVA like other languages.
FYI:
Speaking the Java language without an accent: http://www.ibm.com/developerworks/java/library/j-noaccent.html?ca=drs-

Tuesday, December 02, 2008

some gcc extensions in the linux kernel

Here are some gcc extensions syntax in the linux kernel.
1. typeof(VARIABLE): You can find this at list_head related macros
2.range extension
3.zero-length arrays. IEEE 1394.
4. __builtin_expect. Layer II entry point use likely() and unlikely()
5.__builtin_prefetch. You can find this at list_head related macros

More details, visit IBM developer works
FYI:
IBM GCC hacks in the linux kernel

Tuesday, November 25, 2008

doxygen addon- Moritz

If you need more template for output document of doxygen, try this open source-Moritz.

FYI:
http://sourceforge.net/projects/moritz

Tuesday, October 14, 2008

Change pipe to non-blocking mode

The default pipe(...) is one blocking fd. If you need non-blocking IO, you can refer fowling sample code:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(void) {
int fd[2], pipeAttr;
/*fd[0] for reader, fd[1] for writer*/
pipe(fd);
fnctl(fd[0], pipeAttr, F_GETFL);
pipeAttr |= O_NONBLOCK;
fnctl(fd[0], F_SETFL,
pipeAttr);
do_something(fd);
close(fd[0]);
close(fd[1]);
}
viod do_something(int fd[]) {
/*......*/
}

Zombie while create child thread

I use pthread_create(...) to generate child thread. The child thread becomes zombie after I termite program. After some "google" pages, the answer comes out: join child thread at main process.

errno.h

If you want to use errno at c program, you must include errno.h not declare "extern int errno".

char *strerror(int) is used to display error text.

There are two related header files at kernel source directory:
include/$(ARCH)/errno.h
asm-generic/errno-base.h

Saturday, May 17, 2008

jiffies comparison

If you want to compare time in kernel module, you can user flowing macro to avoid jiffies overflow :
/*in kernel/linux/include/linux/jiffies.h*/
time_after(a,b)
time_before(a,b)
time_after_eq(a,b)
time_before_eq(a,b)

If you compare jiffies directly, you will get wrong result sometimes.

Monday, January 07, 2008

Translate Decimal / IP dotted quad

Here are simple functions to translate decimal/ip dotted quad in python.
Usage:
>dot2dec("64.233.189.99")
1089060195L
>dec2dot(1089060195L)
'64.233.189.99'
>
import types
def dot2dec(ipForm, useHex = False):
if type(ipForm) == types.StringType:
ipf = ipForm.split(".")
elif type(ipForm) in (types.ListType, types.TupleType):
ipf = ipForm
elif type(ipForm) in (types.LongType, types.IntType):
return None
return reduce(lambda a,b: long(a)*256 + long(b), ipf)

def dec2dot(numbericIP):
if type(numbericIP) == types.StringType and not numbericIP.isdigit() :
return None
numIP = long(numbericIP)
return "%d.%d.%d.%d" % ((numIP>>24)&0xFF, (numIP>>16)&0xFF, (numIP>>8)&0xFF, numIP&0xFF)




FYI:
python google group

Thursday, January 03, 2008

Apache POI

Apache announce new release of POI. Current version is 3.01 beta. POI is java implementation of the OLE 2 compound document format.
FYI:
Apache POI project

Tuesday, December 11, 2007

C99

There are some features defined by C99:

1.set initial values when allocate new data structure variable
typedef struct humanInfo_s {
char *name;
int age;
}humanInfo_t;

humanInfo obj = {.name="YUNG"};
2. Variable Declarations does not limit on the top of the function body.

3. inline function.

There some many defines in C99 , but I do not list it.
FYI:
ISO/IEC JTC1/SSC22/WG14-C

Friday, November 23, 2007

iptables

If there are many tables must be update, you have to create new handel when table changes.

iptc_handle_t myhandle = NULL;
if (myhandle)
 iptc_free(&myhandle);
myhandle = create_handle(currentTable, "modprobe");
if (noflush == 0) {
 for_each_chain(flush_entries, verbose, 1, &myhandle);
 for_each_chain(delete_chain, verbose, 0, &myhandle) ;
}


FYI:
iptables-save.c
netfilter

Wednesday, October 24, 2007

jQuery

jQuery is a javascript tool. It can simplify the development processing of ajax.

FYI:
jQuery
IBM developerWorks about JQuery: Simplify Ajax development with jQuery

Sunday, September 24, 2006

Wednesday, February 15, 2006

JFrame.show()

JFrame.show() ==>Deprecated. As of JDK version 1.5, replaced by setVisible(boolean)

javax.swing.SpringLayout ==>add from 1.4. SpringLayout is a very flexible layout manager that can emulate many of the features of other layout managers.

URL:
How to Use SpringLayout