论坛首页 编程语言技术论坛

一段从 tcpdump剥离出来 读取timeval变为hh:mm:ss的源码

浏览 2089 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-05-04  
C
gmt2local.c:
int32_t
gmt2local(time_t t)
{
	register int dt, dir;
	register struct tm *gmt, *loc;
	struct tm sgmt;

	if (t == 0)
		t = time(NULL);
	gmt = &sgmt;
	*gmt = *gmtime(&t);
	loc = localtime(&t);
	dt = (loc->tm_hour - gmt->tm_hour) * 60 * 60 +
	    (loc->tm_min - gmt->tm_min) * 60;

	/*
	 * If the year or julian day is different, we span 00:00 GMT
	 * and must add or subtract a day. Check the year first to
	 * avoid problems when the julian day wraps.
	 */
	dir = loc->tm_year - gmt->tm_year;
	if (dir == 0)
		dir = loc->tm_yday - gmt->tm_yday;
	dt += dir * 24 * 60 * 60;

	return (dt);
}


tcpdump.c
int tflag=1;

cast 't'  //如果在参数中有指定
  --tflag;
  break;

if (tflag > 0)
  thiszone = gmt2local(0);

util.c
void
ts_print(register const struct timeval *tvp)
{
	register int s;
	struct tm *tm;
	time_t Time;
	static unsigned b_sec;
	static unsigned b_usec;

	switch(tflag) {
	case 1: /* Default */
		s = (tvp->tv_sec + thiszone) % 86400;
		(void)printf("%02d:%02d:%02d.%06u ",
			     s / 3600, (s % 3600) / 60, s % 60,
			     (unsigned)tvp->tv_usec);
		break;
	case -1: /* Unix timeval style */
		(void)printf("%u.%06u ",
			     (unsigned)tvp->tv_sec,
			     (unsigned)tvp->tv_usec);
		break;
	case -2:
		if (b_sec == 0) {
			printf("000000 ");
		} else {
			int d_usec = tvp->tv_usec - b_usec;
			int d_sec = tvp->tv_sec - b_sec;

			while (d_usec < 0) {
				d_usec += 1000000;
				d_sec--;
			}
			if (d_sec)
				printf("%d. ", d_sec);
			printf("%06d ", d_usec);
		}
		b_sec = tvp->tv_sec;
		b_usec = tvp->tv_usec;
		break;
	case -3: /* Default + Date*/
		s = (tvp->tv_sec + thiszone) % 86400;
		Time = (tvp->tv_sec + thiszone) - s;
		tm = gmtime (&Time);
		if (!tm)
			printf("Date fail  ");
		else
			printf("%04d-%02d-%02d ",
				   tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
		printf("%02d:%02d:%02d.%06u ",
			   s / 3600, (s % 3600) / 60, s % 60, (unsigned)tvp->tv_usec);
		break;
	}
}
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics