2013年12月21日星期六

万年历程序

#include
#include
#include

int week(int y,int m,int d);//函数声明

void main()
{
    //初始化月份的天数
    int monthday[12]={31,28,31,30,31,30,31,31,30,31,30,31};

    int y,w,i,m=1,d=1;
    printf("请输入一个年份yyyy:\n");
    scanf("%d",&y);

    //如果是闰年,修改第二个月天数
    if ( (y % 4 == 0 && y % 100 != 0)|| y % 400 == 0 ){
        monthday[1]=29;
    }


    for(m=1;m<=12;m++){
        //循环打印每个月
        printf("\n %d年,%d月\n",y,m);
        printf(" 日  一  二  三  四  五  六 \n");

        for (d=1;d<=monthday[m-1];d++){
            //获取对应的星期
            w=week(y,m,d);
            if(d==1){
                //打印每月第一天前面的空格
                for (i=0;i                    printf("%3c ",' ');
                }
            }

            printf("%3d ",d);

            //每星期换行
            if(w==6) printf(" \n");
        }

        printf("\n\n输入任意字符继续\n");
        getch();
    }

    system("pause");
}

int week (int y,int m,int d)
{
    //http://hi.baidu.com/wlzqi/blog/item/65b16b606403df44ebf8f8a2.html
    int w;
    if((m==1)||(m==2)){
        y--;
        m+=12;
    }
    w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400+1)%7;
    return w;
}

2013年12月10日星期二

grep 用法

我本不想写这篇文章,首先我觉得这些东西大家肯定都知道,其次就算真不知道还有手册。
直到那天面试的时候我碰到一个哥们,我问他grep你都知道哪些选项?他告诉我,只有-r。我当时就乐了,既然grep是你常用的命令,你凭什么只 知道-r?他回答说,他只想把精力放到内核上,没有时间来学习这些东西。我笑,正是因为你没有时间,所以你才应该提高你的工作效率,而熟悉命令行显然是 Linux上一种提高工作效率的方式。有句老话说得好:“磨刀不误砍柴功。”
有的同学可能觉得我在提倡死记硬背了,事实上我比你更反对中国教育的那种死记硬背。我的观点很简单:既然你用得多,那么有些东西,比如grep的一些选项,自然而然就应该记住了,无须刻意去背。
所以,我在这里以grep为例来展示一下。注意,以下内容没有参考一眼grep的手册。
grep最常用的选项可能是-i,-n和-r了,至少于我如此。-i是忽略大小写,-n可以告诉你找到的东西在文件的哪一行。-r或者-R(看你愿不愿意多按个shift键了),可以去递归一个目录。
-A和-B,你可能就用的比较少了,前者制定显示匹配到的那一行之后的几行,后者指定之前的,比如grep -A 3 -B 4就是说也要显示匹配到的那一行之前的4行和之后的3行,可见A是After,B是Before。用得着刻意去记嘛?显然不用。
-I(大写i)可能用得就更不多了,可惜啊,它非常有用。比如你编译出的内核二进制和你的源代码在同一个目录时,你grep一些字符串的时候会发现一些.o文件中也可以找到,很明显它不是我们想要的,这时候-I就派上用场啦!它告诉grep去忽略二进制文件。
这让我想到了另一个--exclude(我记得似乎没有短选项与之对应),顾名思义,它是用来排除一些文件。比如你编译的内核目录下还有*.cmd这种文件的话,它不是二进制,所以-I排除不掉,这时候你就可以用--exclude "*.cmd"了。
-H,这个用得更少了,你一般不会需要它,因为grep默认就会输出文件名。然而,当grep与find联手的时候就不会了(至于为什么,留给你作 为课后作业),这时候你就要用到-H了。比如,我在内核源代码目录下查找CONFIG_DEBUG_KMEMLEAK定义在哪,我通常这么做:find . -iname 'kconfig*' -exec grep -Hwn DEBUG_KMEMLEAK '{}' \;
我上面用到了另一个选项-w,看见了嘛?它可能是另外一个被严重忽视了的选项,仅次于-I啊!它的意思是告诉grep我所查找的是一个完整的单词, 也就是说,当你找DEBUG_KMEMLEAK的时候它不会给你找出DEBUG_KMEMLEAK_EARLY_LOG_SIZE,你懂的。这可以省去你 手工去加\b了。
噢,我差点儿忘了亲爱的-e,多数情况下你也不需要它,因为grep后面接的就是一个regrex嘛!-e神马时候派上用场呢?我建议你在这里仔细 想想,一个很特殊的情况——我要搜索的字符串以"-"开头时!比如我要搜索"-wangcong"这个字符串,直接grep "-wangcong"显然是不行滴!grep会认为那是"-w -a -n -g -c -o -n -g",无论你怎么加引号!一种解决方法是加反斜线,而另一种方法就是-e "-wangcong"了。顺便说一句,使用多次-e就相当于进行一个“或”操作,所以grep "vmx\|svm"就等价于grep -e vmx -e svm。
-o我估计用的人也不多,它的意思是只输出匹配到的东西,同一行的其它东西不输出。例如,我想搜索printk.c中全部的C语言字符串时,我会这 么做:grep -o '".*"' kernel/printk.c,有点儿类似于strings kernel/printk.o。
-b,知道这个人的灰常少了吧?如果你知道,恭喜你晋级grep高手级别了!我承认我只用过它一次,是在一个脚本中,我想知道某个“字符串”出现在 文件的第几个字节。我印象中这里是有bug的,因为我当时总得不到正确的结果,当然也有可能是我理解不对,没看手册而且没有再次实验,所以这个问题就留给 你了。:-)
-q嘛,大家都知道,脚本中常用。
-c嘛,比如统计CPU个数:grep -c '^processor' /proc/cpuinfo,实在没必要多一个管道去 grep '^processor' /proc/cpuinfo | wc -l。
好了,我就想起来这么多了,欢迎补充。我觉得一个好的Linux程序员应该对他/她敲出的每一行命令的每一个选项都精益求精,不多不少。
我知道有些人对此不屑一顾,嗤之以鼻,我只想告诉这些人一句话:“天下大事必做于细,天下难事必做于易。”你要是认为我这是在教育你,你就错大了,我对教育人,尤其是教育你这种人,没任何兴趣!你倒找给我钱我都不会稀罕去教育你!有他妈的多远给我滚他妈的多远!
附我窜改的《见与不见》:
你知,或者不知它/命令就在那里/不悲不喜
你看,或者不看它/手册就在那里/不来不去
你爱,或者不爱它/程序就在那里/不吵不闹
你用,或者不用它/二进制就在你的机器上/不亢不卑
去了解它们/或者/让它住进你的心里
人机合一/融为一体

shell中if的相关参数

[ -a FILE ]     如果 FILE 存在则为真。
[ -b FILE ]     如果 FILE 存在且是一个块特殊文件则为真。
[ -c FILE ]     如果 FILE 存在且是一个字特殊文件则为真。
[ -d FILE ]     如果 FILE 存在且是一个目录则为真。
[ -e FILE ]     如果 FILE 存在则为真。
[ -f FILE ]     如果 FILE 存在且是一个普通文件则为真。
[ -g FILE ]     如果 FILE 存在且已经设置了SGID则为真。
[ -h FILE ]     如果 FILE 存在且是一个符号连接则为真。
[ -k FILE ]     如果 FILE 存在且已经设置了粘制位则为真。
[ -p FILE ]     如果 FILE 存在且是一个名字管道(F如果O)则为真。
[ -r FILE ]     如果 FILE 存在且是可读的则为真。
[ -s FILE ]     如果 FILE 存在且大小不为0则为真。
[ -t FD ]     如果文件描述符 FD 打开且指向一个终端则为真。
[ -u FILE ]     如果 FILE 存在且设置了SUID (set user ID)则为真。
[ -w FILE ]     如果 FILE 如果 FILE 存在且是可写的则为真。
[ -x FILE ]     如果 FILE 存在且是可执行的则为真。
[ -O FILE ]     如果 FILE 存在且属有效用户ID则为真。
[ -G FILE ]     如果 FILE 存在且属有效用户组则为真。
[ -L FILE ]     如果 FILE 存在且是一个符号连接则为真。
[ -N FILE ]     如果 FILE 存在 and has been mod如果ied since it was last read则为真。
[ -S FILE ]     如果 FILE 存在且是一个套接字则为真。
[ FILE1 -nt FILE2 ]     如果 FILE1 has been changed more recently than FILE2, or 如果 FILE1 exists and FILE2 does not则为真。
[ FILE1 -ot FILE2 ]     如果 FILE1 比 FILE2 要老, 或者 FILE2 存在且 FILE1 不存在则为真。
[ FILE1 -ef FILE2 ]     如果 FILE1 和 FILE2 指向相同的设备和节点号则为真。
[ -o OPTIONNAME ]     如果 shell选项 “OPTIONNAME” 开启则为真。
[ -z STRING ]     “STRING” 的长度为零则为真。
[ -n STRING ] or [ STRING ]     “STRING” 的长度为非零 non-zero则为真。
[ STRING1 == STRING2 ]     如果2个字符串相同。 “=” may be used instead of “==” for strict POSIX compliance则为真。
[ STRING1 != STRING2 ]     如果字符串不相等则为真。
[ STRING1 < STRING2 ]     如果 “STRING1” sorts before “STRING2” lexicographically in the current locale则为真。
[ STRING1 > STRING2 ]     如果 “STRING1” sorts after “STRING2” lexicographically in the current locale则为真。
[ ARG1 OP ARG2 ]     “OP” is one of -eq, -ne, -lt, -le, -gt or -ge. These arithmetic binary operators return true if “ARG1” is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to “ARG2”, respectively. “ARG1” and “ARG2” are integers.
源于:http://hi.baidu.com/piaoliuzaiwai/blog/item/2000f3fc9ec960fcfc037f7f.html

使用cscope阅读内核源代码

代码阅读工具简介
对于学习Linux内核的人来说,源代码的阅读尤为重要。因为所有设计思想、内部机制都是以代码的形式实现,所有的资料也都是为了更好的诠释代码。 那么一个好的阅读工具,能够提高阅读的效率和效果。常见的代码阅读工具有,KScope、Source Navigator、Source Insight、lxr、Cscope等。
* KScope[1]是一款KDE桌面环境下的源代码阅读、浏览工具,自带了编辑功能。比较适合C语言编写的大型项目。KScope底层使用Cscope作为源代码的分析引擎。多数发行版都提供了KScope的安装包。
* “Source Navigator”是红帽子公司的,以GNU GPL发布,可从官方网站[2]下载使用。
* “Source Insight”目前只有Windows平台的,官方网站[3]。需要注册才能使用,或者从网上下载注册机生成注册码。在Linux下通过wine模拟虽然可以方便使用,但它毕竟是Windows平台的东西,并不能很自由的使用。
* lxr(linux cross reference)[4]为程序源代码建立索引数据库,利用perl脚本CGI动态生成包含源码的web页面,你可以用任何一种浏览器查阅。缺点是需要服务器支持,还有速度。
* “Cscope”[5]为终端下的代码阅读工具,资源消耗少,对那些忠于命令行的行操作的人,使用起来更加方便、灵活。这也是这篇文章推荐使用的一个重要原因。也有人把Cscope和Emasc绑定阅读源码。当然工具的选取,也取决于个人习惯。
Vim+Ctags+Cscope
cscope的工作需要vim、ctags的配合,它们都是基于命令行的。在Ubuntu下,用户只需执行“sudo apt-get install cscope cscope-indexer ctags vim”即可完成软件安装。下面只是给出了三种工具的常用方法,更多功能可查看man手册,或者官方文档。
Vim
vim被看作是专门为程序员打造的文本编辑器,其丰富的编辑命令都是常用的简单字符,用户很容易上手。vim可对180多种语言的语法高亮,对C语 言自动缩进,真则表达式字符匹配查找,功能强大,并支持多个操作系统平台。关于vim的使用,这里不做讲解。vim中文文档[6]。
Ubuntu系统自带的vim,没有语法加亮功能。上面的安装命令已经更新了vim,在vim 配置文件 ~/.vimrc中 添加一行 “syntax on”,这样在vim中打开的源码就有了语法高亮显示。
vim自带了很多颜色主题,可以直接选取下面一行添加到vim配置文件当中,重新打开vim即可生效。
colorscheme elflord “我使用这个
colorscheme darkblue
colorscheme evening
colorscheme murphy
colorscheme torte
colorscheme desert
Ctags
在源代码根目录下执行 ctags -R 命令用来为程序源代码生成标签文件,其-r选项表示递归操作,同时为子目录也生成标签文件。vim利用生成的标签文件,可以进行相应检索、并在不同的文件C语言元素之间来回切换。
在vim中ctags的简单使用
1) 跳转到指定的函数进入vim后,用 “:tag func_name“ 跳到函数func_name处。使用tag命令时,可以使用TAB键进行匹配查找,继续按TAB键向下切换。
某个函数有多个定义时
:tag
跳到第一个定义处,优先跳转到当前文件
:tnext
跳到第一个
:tfirst
跳到前count个
:[count]tprevious
跳到后count个
:[count]tnext
跳到最后一个
:tlast
你也可以在所有tagname中选择:
:tselect tagname
如果想跳到包含block的标识符:“tag /block” 然后用TAB键来选择。这里’/'就是告诉vim ‘block’是一个语句块标签。
2)用“CTRL + ]“快捷键,跳转到光标所在函数标识符的定义处。
3)使用“CTRL + T”退回上层。 如果想在以write_开头的标识符中选择一下, :tselect /^write_ 这里,’^'表示开头,同理,’$'表示末尾。多个同名的标识符
Cscope
运行cscope命令,出现两个面板,上方是一个查找结果的显示面板,下方是一个查找条件指定面板。使用TAB键在两个面板间切换,也可使用上下左 右方向件和翻页键在同一面板内贴换位置。选中显示面板的某个项,回车即可进入该文件,这是调用vim打开文件,这时就可以结合ctags使用了。当然也可 以直接使用vim打开文件,结合ctags阅读源码。
使用前,必须现使用“cscope-indexer -r”命令递归生成索引信息文件。特殊情况下,还需要用户使用find命令,主动生成索引信息文件,并指定给cscope工具。 cscope提供了如下九种查询方式:
Find this C symbol:
#查找指定的C符号
Find this global definition:
#查找指定的全局定义
Find functions called by this function:
#查找指定函数调用的函数
Find functions calling this function:
#查找调用指定函数的函数
Find this text string:
#查找字符串
Change this text string:
#修改指定字符串
Find this egrep pattern:
#查找匹配字符
Find this file:
#查找指定文件
Find files #including this file:
#指定引用头文件进行查找
在对应某一项中输入查找条件,回车即可进行查询,并将结果显示在显示面板。
应用实例
下面以使用cscope阅读内核源代码为例:
$ wget http://kernel.org/pub/linux/kernel/v2.6/linux-2.6.27.6.tar.bz2
#从Linux内核官网下载内核源代码
$ tar xvfj linux-2.6.27.6.tar.bz2
#解压文件
$ cd linux-2.6.27.6
#进入源代码根目录
$ ctags -R
#递归生成标签文件
$ cscope-indexer -r
#递归生成索引信息文件
$ cscope
#使用cscope阅读源码
对于内核源代码也可以直接使用“make cscope”、“make tags”生成相应的索引信息、标签文件。
标签文件、索引信息文件只需要第一次或者代码发生变动时生成,以后使用直接运行cscope即可。
总结
要达到灵活应用的境界,还必须熟练结合其他工具,如grep、正则表达式等的使用。其中有很多技巧性的东西需要去不断总结、积累。
[1] http://kscope.sourceforge.net/
[2] http://sourcenav.sourceforge.net/
[3] http://www.sourceinsight.com/
[4] http://lxr.linux.no/
[5] http://cscope.sourceforge.net/
[6] http://vcd.gro.clinux.org/

并发编程

http://concur.rspace.googlecode.com/hg/talk/concur.html#hello
http://www.haskell.org/haskellwiki/Parallelism_vs._Concurrency
http://greenteapress.com/semaphores/

https://blog.heroku.com/archives/2013/2/24/concurrency_is_not_parallelism
http://supertech.csail.mit.edu/cilk/



2013年8月30日星期五

meta programming in python

http://stackoverflow.com/questions/17330160/python-how-does-decorator-property-work

http://martyalchin.com/2007/nov/23/python-descriptors-part-1-of-2/

http://users.rcn.com/python/download/Descriptor.htm

http://www.ibm.com/developerworks/library/os-pythondescriptors/

2013年8月26日星期一

vi 行编辑模式


Selecting columns with visual block mode

#22
If you want to edit several adjacent lines with a similar format, you might save a lot of time by making a columnar selection. This episode will demonstrate how to achieve this using Vim’s visual block mode.

Download

OGG 5.5 MB
Quicktime 8 MB
Visual block mode allows you to select a rectangular section of text. From normal mode, you can enter visual block mode by pressing ctrl-v.
In most text editing environments, if you want to replace some text, you can just start typing and the replacement will overwrite the selection. But Vim’s visual modes are similar to normal mode, in that each key will execute a command. Here are some of the commands covered in this episode:
command action
c change selection (delete and switch to insert mode)
I insert in front of cursor
A append after cursor
r replace every character in selection
d delete selection
o toggle cursor to opposite corner

2013年8月1日星期四

screen命令

linux screen 命令详解 - [linux]

版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://bjzero.blogbus.com/logs/30983025.html

linux screen 命令详解
2008-10-22 15:05
功能说明:

使 用telnet或SSH远程登录linux时,如果连接非正常中断,重新连接时,系统将开一个新的session,无法恢复原来的 session.screen命令可以解决这个问题。Screen工具是一个终端多路转接器,在本质上,这意味着你能够使用一个单一的终端窗口运行多终端 的应用。

语  法:

screen [-AmRvx -ls -wipe][-d <作业名称>][-h <行数>][-r <作业名称>][-s ][-S <作业名称>]

补充说明:

screen为多重视窗管理程序。此处所谓的视窗,是指一个全屏幕的文字模式画面。通常只有在使用telnet登入主机或是使用老式的终端机时,才有可能用到screen程序。

参  数:

-A  将所有的视窗都调整为目前终端机的大小。
-d <作业名称>  将指定的screen作业离线。
-h <行数>  指定视窗的缓冲区行数。
-m  即使目前已在作业中的screen作业,仍强制建立新的screen作业。
-r <作业名称>  恢复离线的screen作业。
-R  先试图恢复离线的作业。若找不到离线的作业,即建立新的screen作业。
-s  指定建立新视窗时,所要执行的shell。
-S <作业名称>  指定screen作业的名称。
-v  显示版本信息。
-x  恢复之前离线的screen作业。
-ls或--list  显示目前所有的screen作业。
-wipe  检查目前所有的screen作业,并删除已经无法使用的screen作业。

常用screen参数:

screen -S yourname -> 新建一个叫yourname的session
screen -ls -> 列出当前所有的session
screen -r yourname -> 回到yourname这个session
screen -d yourname -> 远程detach某个session
screen -d -r yourname -> 结束当前session并回到yourname这个session

在每个screen session 下,所有命令都以 ctrl+a(C-a) 开始。

C-a ? -> Help,显示简单说明
C-a c -> Create,开启新的 window
C-a n -> Next,切换到下个 window
C-a p -> Previous,前一个 window
C-a 0..9 -> 切换到第 0..9 个window
Ctrl+a [Space] -> 由視窗0循序換到視窗9
C-a C-a -> 在两个最近使用的 window 间切换
C-a x -> 锁住当前的 window,需用用户密码解锁
C-a d -> detach,暂时离开当前session,将目前的 screen session (可能含有多个 windows) 丢到后台执行,并会回到还没进 screen 时的状态,此时在 screen session 里    每个 window 内运行的 process (无论是前台/后台)都在继续执行,即使 logout 也不影响。
C-a z -> 把当前session放到后台执行,用 shell 的 fg 命令則可回去。
C-a w -> Windows,列出已开启的 windows 有那些
C-a t -> Time,显示当前时间,和系统的 load
C-a K -> kill window,强行关闭当前的 window
C-a [ -> 进入 copy mode,在 copy mode 下可以回滚、搜索、复制就像用使用 vi 一样
    C-b Backward,PageUp
    C-f Forward,PageDown
    H(大写) High,将光标移至左上角
    L Low,将光标移至左下角
    0 移到行首
    $ 行末
    w forward one word,以字为单位往前移
    b backward one word,以字为单位往后移
    Space 第一次按为标记区起点,第二次按为终点
    Esc 结束 copy mode
C-a ] -> Paste,把刚刚在 copy mode 选定的内容贴上

--End--

关于NAT模拟



As we talk yesterday,  I think you have to setup the environment for yourself, because the virtual machine image is too large.

   First I will give an introduction on how to emulate the NAT behavior. Then I’ll give you the steps on how to set it up.

   I have not fully tested on them for lack of machine(I use vm on laptop, the memory is only 4G), maybe you can help test  them and report if any problem and we can review It together.

   To better understand different NAT behavior, there is rfc4787: Network Address Translation (NAT) Behavioral Requirements  for Unicast UDP, if you don’t have time, you don’t have to read it now and refer to it later when necessary. However, I strongly suggest that you take a look at the paper “Improving NAT/Software compatibility through  Flexible NAT Emulation Software” of FlexNES, it gives introduction on what behaviors of NAT FlexNES can emulate, and those behavioral are more related to ICE connection setup.

   Pre-requirements: You have to setup VM with two network interface, say eth0 and eth1, eth0 connected to the public network(in office, such as 10.224.173.97, you can use DHCP to get the ip addr or set it as static ip), and eth1 connected to the private network as the gateway(192.168.1.1). Then you have to turn on the ipforward.

  Then you can set the test client using it as the gateway, set the ip to the internal ip.

  
As written in previous mail. There are two possible solutions(have some updates here):

1.       Use iptables NAT, iptables NAT is port restricted + symmetric, the NAT behavior changes case by case.

a. if with --ramdom param, it’s symmetric, else:
b. when there is one client behind the NAT, then it’s port restricted.
c. if more than one clients behind the NAT, it MAY be symmetric.
d. p2p connection by STUN is impossible even when two peer are both behind iptables NAT. The reason is because in this cases(during the hole punching process) there is one NAT behave like symmetric.

Other characters about iptables NAT, and it can’t be changed
a. Mapping refresh (30 second)
b. iptable NAT will reserve port, and will solve conflict.

reference links:
iptablesudp穿越基础篇
iptablesudp穿越实用篇----iptablesnatcheck
Correctly classifying iptables NAT beahaviour

The command is simple

iptables -F                          #clear rules in all table, so all traffics are not filtered by default
iptables -t nat -F               #clear the NAT table, no need if “iptables -F” excuted
iptalbes -t nat -A POSTROUTING -o eth0 -j MASQUERADE           #add rule to replace the source ip using the external ip.
2.       Use FlexNES, recommend this one. FlexNES has emulated the main NAT behaviors relating to UDP connectivity

a. Address and Port mapping.
b. Port Assignment.
c. Port Parity.
d. Mapping Refresh.
e. Filtering behavior.
f. Hairpinning.

And as I stated before:

 - Full Cone: Endpoint-Independent mapping + Endpoint-Independent filtering
- Restricted Cone: Endpoint-Independent mapping + Address-Dependent filtering
- Port Restricted Cone: Endpoint-Independent mapping + Address and Port-Dependent filtering
- Symmetric: Address and Port-Dependent Mapping +  Address and Port-Dependent filtering

To compile FlexNES,
you have to compile it in linux kernel 2.6(I use centos5.4), and install the dependences:
1. boost-dev. (yum install boost-devel)
2. Libnet. (http://packetfactory.openwall.net/projects/libnet/)
3. Netfilter dev( I have downloaded the centos 5.4 rpms, and they are under directory “/root/flexNES-1.0/src” in 10.224.195.53, username: “root”, password: “pass”, you can copy them using scp, port 22.

    - iptables-1.3.5-5.6.1.el5.i386.rpm
    - iptables-devel-1.3.5-5.6.1.el5.i386.rpm
    - libnetfilter_queue-1.0.0-1.el5.i386.rpm
    - libnetfilter_queue-devel-1.0.0-1.el5.i386.rpm
    - libnfnetlink-1.0.1-1.el5.i386.rpm
    - libnfnetlink-devel-1.0.1-1.el5.i386.rpm

    You can use rpm –ivh [rpmpkg] to install them.
4. Some source files need to modified to make the compiler happy, you can also copy the source file there.
5. “make depend;make” will generate the binary file.
Testing: using natcheck, source file can be downloaded http://midcom-p2p.cvs.sourceforge.net/viewvc/midcom-p2p/web/ , you need at least three servers for the test(or you can use one server with 3 ip)

./natserver 1
./natserver 2
./natserver 3
Besides, you have to change the hardcoded value in natcheck.c, or you can walk around this by setting them in “/etc/resolv.conf” to the ip addr of the servers.





Possibly two approaches now:

1.       Using iptables
2.       Using 3rd party tools build directly using netfilter.

Still in progress, and not tested yet. Will update with more clear guides later when tested on the solutions. 


Following is for who interested in the details.


Solution 1
----------------------

Firewalling with netfilter/iptables

介绍了用iptable做防火墙的配置,主要介绍了filternat两种table的使用。

Advanced Features of netfilter/iptables
介绍了用iptable的一些高级功能,比如用来做负载均衡,流量控制,按时间进行访问控制,限制链接数等。

NAT - Network Address Translation
详细介绍了linux用来做NAT的原理和配置。

NAT-HOWTO

NAT可以分为下面几种类型:

• Full Cone: A full cone NAT is one where all requests from the same internal IP address and port are mapped to the same external IP address and port. Furthermore, any external host can send a packet to the internal host, by sending a packet to the mapped external address.

• Restricted Cone: A restricted cone NAT is one where all requests from the same internal IP address and port are mapped to the same external IP address and port. Unlike a full cone NAT, an external host (with IP address X) can send a packet to the internal host only if the internal host had previously sent a packet to IP address X.

• Port Restricted Cone: A port restricted cone NAT is like a restricted cone NAT, but the restriction includes port numbers. Specifically, an external host can send a packet, with source IP address X and source port P, to the internal host only if the internal host had previously sent a packet to IP address X and port P.

• Symmetric: A symmetric NAT is one where all requests from the same internal IP address and port, to a specific destination IP address and port, are mapped to the same external IP address and port. If the same host sends a packet with the same source address and port, but to a different destination, a different mapping is used. Furthermore, only the external host that receives a packet can send a UDP packet back to the internal host. 

这里实际上有两层意思,一个是出去的连接ip,port的分配(mapping),一个是允许外面什么样的包能进来(filter)

我们用iptable是可以来模拟NAT的,但这种NAT具体又是哪种类型的呢?如何才能模拟不同类型的NAT呢?这些问题在网上也是众说纷纭,下面给一个相对比较权威的答案。

“As I wrote at netfilter-devel around May this year,

- According to the terminology of RFC 3489, netfilter implements port
restricted cone NAT. If the –random flag is specified to the
SNAT/MASQUERADE/… targets, it's better described as a symmetric NAT.
- According to the terminology of RFC 4787 and RFC 5382, netfilter
implements
- endpoint-independent mapping. If the –random flag is
specified to the SNAT/MASQUERADE/… targets, it's an
address and port-dependent mapping.
- address and port-dependent filtering.


链接在这:Correctly classifying iptables NAT
beahaviour


下面是我的一些理解:

要模拟不同的NAT类型,实际是就是模拟mappingfiltering

 core类型,三种mapping策略都是一样的,不同的只是filtering策略; mapping策略就是对于同样的内网(ip,port),分配同样的外网(ip,port)。如果我们使用SNAT或者MASQUERADE动作,就可 以仅仅替换ip,端口维持不变,这样就模拟了mapping。而filtering策略,则有iptable中的filter表来做相应的处理;由于 Address Restricted ConePort Restricted Cone是需要记录状态的,记录之前内网的ip,port有没有给相应的dst_ip或者(dst_ip,dst_port)发送过数据。在创建 filter的规则时,是可以指定状态的(具体见Firewalling with netfilter/iptables),对于Address Restricted Cone,状态应该是RELATED,对于Port Restricted Cone,状态则是ESTABLISHEDiptable中默认是ESTABLISHED,即Port Restricted的。

而对于Symmetricmapping策略就不一样了,如果SNAT或者MASQUERADE是指定的–random参数,那就是Symmetric类型。Filtering默认就是和Port Restricted Cone一样。

Solution 2
----------------------








2013年7月7日星期日

puppet, fabric资源

http://www.puppetcookbook.com/

bash的一些零碎记录

$?来显示前一个命令的执行结果
$! 进程号

set -e

执行bash命令时,如果任何一个命令出现错误,那么立刻终止执行。也就是说,其中的任何一个命令都不能返回错误。

2013年5月29日星期三

timer wrap

http://yarchive.net/comp/linux/timer_wrapping_c.html

http://stackoverflow.com/questions/8206762/how-does-linux-handle-overflow-in-jiffies

http://stackoverflow.com/questions/8206762/how-does-linux-handle-overflow-in-jiffies

2013年5月16日星期四

NTP



通过date命令可直接现在的时间戳
# date +%s
1265851947
也可以得到指定时间的时间戳
# date -d "2007-07-30 9:30" +%s
1185759000
然后我们可以将它们转换为系统的时间格式
# date -d '1970-01-01 UTC 1265851947 sec' +"%F %T"
2010-02-11 09:32:27
# date -d '1970-01-01 UTC 1185759000 sec' +"%F %T"
2007-07-30 09:30:00

For example, open /etc/ntp.conf file using vi text editor:
# vi /etc/ntp.conf
Locate server parameter and set it as follows:
server pool.ntp.org
Save the file and restart the ntpd service:
# /etc/init.d/ntpd start
You can synchronize the system clock to an NTP server immediately with following command:
# ntpdate pool.ntp.org

2013年5月14日星期二

gcov: lots of EOF in gcov file

You have to run gcov in the same directory as the .cpp file, otherwise it
gives an error message about being unable to find it (even with a path.)  This
works:
 
 
python one 
http://nedbatchelder.com/code/coverage/branch.html 

2013年5月10日星期五

fast time in linux

http://fasttime.sourceforge.net/doc/internal.html
http://tsc-xluo.sourceforge.net/

2013年4月29日星期一

latex的参考

http://stackoverflow.com/questions/1017055/get-started-with-latex-on-linux

http://www.maths.tcd.ie/~dwilkins/LaTeXPrimer/

https://launchpad.net/rubber/

http://www.lyx.org/Download

http://en.wikibooks.org/wiki/LaTeX

http://miktex.org/download

http://www.tug.org/texlive/

du/df howto


Df命令是linux系统以磁盘分区为单位查看文件系统,可以加上参数查看磁盘剩余空间信息,命令格式:

df -hl

显示格式为: 

文件系统              容量 已用 可用 已用% 挂载点 

Filesystem            Size Used Avail Use% Mounted on

/dev/hda2              45G   19G   24G 44% /

/dev/hda1             494M   19M 450M   4% /boot

/dev/hda6             4.9G 2.2G 2.5G 47% /home

/dev/hda5             9.7G 2.9G 6.4G 31% /opt

none                 1009M     0 1009M   0% /dev/shm

/dev/hda3             9.7G 7.2G 2.1G 78% /usr/local

/dev/hdb2              75G   75G     0 100% /

/dev/hdb2              75G   75G     0 100% /

以上面的输出为例,表示的意思为:

HD硬盘接口的第二个硬盘(b),第二个分区(2),容量是75G,用了75G,可用是0,因此利用率是100%, 被挂载到根分区目录上(/)。

下面是相关命令的解释:

df -hl 查看磁盘剩余空间

df -h 查看每个根路径的分区大小

du -sh [目录名] 返回该目录的大小

du -sm [文件夹] 返回该文件夹总M数

更多功能可以输入一下命令查看:

df --help

du --help


查看硬盘的分区 #sudo fdisk -l

查看IDE硬盘信息 #sudo hdparm -i /dev/hda

查看STAT硬盘信息 #sudo hdparm -I /dev/sda 或 #sudo apt-get install blktool #sudo blktool /dev/sda id

查看硬盘剩余空间 #df -h #df -H

查看目录占用空间 #du -hs 目录名

优盘没法卸载 #sync fuser -km /media/usbdisk

Sphinx PDF with rst2pdf

I deliberately omit word LaT*X in my post to avoid missing people who add '-LaT*X' in search queries. Yes, it is possible to generate PDF with Sphinx without LaT*X in cross-platform way. Yes, on Windows too. You will need only rst2pdf. Actually integration with Sphinx is well described in rst2pdf manual (text and PDF), but people find it hard to find this information, so I'll quote checklist here:
  1. install rst2pdf
  2. register rst2pdf in your conf.py Sphinx config
    extensions = ['sphinx.ext.autodoc','rst2pdf.pdfbuilder']
  3. run
    sphinx-build -bpdf sourcedir outdir
I hope it was helpful. Actually, check the manual - it has some useful options for conf.py and it's more up-to-date.

http://rst2pdf.googlecode.com/svn/trunk/doc/manual.txt

vs2008 replace tab with space

VS2008将原有的tab空格设置为空格符号

1、首先将设置tab的空格缩进:Tools --> Options --> Text Editor”,如果是编写C/C++程序,就打开“C/C++-->Tabs”,在这里,选中“Insert spaces”即可
2、显示空格:ctrl+shift+*快捷键,或者Edit->Advanced->View White Space:
3、转换:选择代码块,Edit->Advanced->Format Selection (Ctrl+K,Ctrl+F:)

Keep tabs on white space in Visual Studio

To turn on visual indicators of whitespace in Visual Studio, use the keyboard chord (Ctrl-R, Ctrl-W) (setting found in Tools > Environment > Options):
image
Instead of nothing:
image
You can now see:
image
By default, when I set the insertion point on line 12 and hit Enter, Visual Studio inserted spaces instead of tabs:
image
To turn this off, change the setting to Keep Tabs in Tools > Options > Text Editor > All Languages > Tabs:
image
image
You can also do Edit > Advanced > Tabify Selected Lines.

vim中转换tab为空格 vim: Convert [tab] to [space] 发布时间:2009-06-29 13:01:13
技术类别:CPLD/FPGA

在vim中,有时需要将tab转换成space。使用ret命令(replace tab)。
[range]ret[ab]! [new-tabstop]

举例:将第一行到文件尾的tab转换成space,每个tab用4个space替代。
:set expandtab
:%ret! 4
如果没有给定4,则用当前的tab宽度设定替换为space。

其它相关命令:
:set tabstop=4        设定tab宽度为4个字符
:set shiftwidth=4     设定自动缩进为4个字符
:set expandtab        用space替代tab的输入
:set noexpandtab      不用space替代tab的输入

2013年2月17日星期日

拷贝保持用户信息

cd /old_dir
find . -depth -print | cpio -pdlmv /new_dir

2013年2月5日星期二

kprobes

http://www.ibm.com/developerworks/library/l-kprobes/index.html

http://lwn.net/Articles/132196/

http://www.redhat.com/magazine/005mar05/features/kprobes/