简易ping程序

简单的ping程序,运行时请不要忘了加sudo命令哦!
啥也不说了,直接上代码~

一、全局变量及函数声明

#define PACKET_SIZE    4096
#define MAX_WAIT_TIME  5
#define MAX_NO_PACKETS 3

//定义发送和接受包的缓冲区
char sendpacket[PACKET_SIZE];
char recvpacket[PACKET_SIZE];

int sockfd, datalen = 56;
int nrecv = 0;
int seq = 0;
int number = 4;

struct sockaddr_in dest_addr; //目的地地址结构变量
pid_t pid;

struct sockaddr_in from;
struct timeval tvrecv;        //定时器结构变量

void statistics(int signo); //统计
unsigned short cal_chksum(unsigned short *addr, int len); //校验和
int pack(int pack_no); //设置icmp报头
void send_packet(void); //发送icmp报文
void recv_packet(void); //接受icmp报文
int unpack(char *buf, int len); //解析ICMP报头
void tv_sub(struct timeval *out, struct timeval *in); //两个timeval结构相减
void alarmhandler(int signo); //计时器处理函数

二、主函数

int main(int argc, char *argv[])
{
	struct hostent *host;
	struct sigaction act;
	
	unsigned long inaddr = 0l;
	int waittime = MAX_WAIT_TIME;
	int size = 50 * 1024;
	
	if(argc < 2)
	{
		printf("usage : %s <hostname/IP> [-t number]\n", argv[0]);
		exit(1);
	}
	
	if(argc == 4)
		number = atoi(argv[3]); //设置ping次数
		
	signal(SIGINT, statistics);
	//程序中断时运行statistics函数
	
	if((host = gethostbyname(argv[1])) == NULL)
	{
		perror("Gethostbyname Error!");
		exit(1);
	}
	
	/*生成使用ICMP协议的原始套接字,需要使用root权限用户*/
	if( (sockfd = socket( AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
	{
		perror("RAW SOCKET error!");
		exit(1);
	}
	
	/*回收root权限,设置当前用户权限*/
	setuid(getuid());
        /*接收缓冲区增大了,为了防止数据包阻塞,所以这里需要修改socket的设置*/
	setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(int));
		
	bzero(&dest_addr, sizeof(struct sockaddr_in));
	dest_addr.sin_family = AF_INET;
	dest_addr.sin_addr = *((struct in_addr *) host -> h_addr);
	
	pid = getpid();
	
	printf("PING %s (%s): %d bytes data in ICMP packets.\n", argv[1], 
		inet_ntoa(dest_addr.sin_addr), datalen);
	
	act.sa_handler = alarmhandler;
	act.sa_flags = 0;
	sigemptyset(&act.sa_mask);
	sigaction(SIGALRM, &act, NULL);
	
	raise(SIGALRM);
	recv_packet();
	return 0;
}

三、处理函数
详细见附件~
ping演示程序

发表评论?

26 条评论。

  1. Thanks. Appreciate all the work you’ve put into writing these.

  2. At present I was so tired, and now this time I have got some rest by seeing this comic YouTube video, thanks, keep it up.

  3. Illinois however | Magic Shows and Birthdays in NJ - pingback on 2013 年 12 月 14 日 在 上午 6:36
  4. Hogan scarpeglamour e chichi hogan scarpe on band hogan olympia uomo crea un mix, una scarpa comoda appear una sneaker, ma dall aspetto poco accidental anche qui si possono scegliere.Scarpe hogan sito ufficiale, hogan insubordinate 2013, scarpe hoganrecent posts paris hilton abbandona la adventures pubblica e confessa con borsa armani 2013 noemi letizia a passeggio con borsa miu miu e con il suo fidanzato,scoppia in.2014 scarpe hogan alternate uomo – su hogan online sitescarpe hogan online armpit ufficiale italia hogan aperture provides the best 2014 scarpe hogan alternate uomo/donna/junior, sconti scarpe hogan insubordinate aperture online.Scarpe hogan olympia uomo 2012 nerocheap hogan shoes aperture accommodate the widest ambit of affluence hogan shoes auction for you chargeless aircraft all over the apple we accept acceptable services, hogan outlet, more.Hogan shoes sku214 ita31car0025 – 88 10 : scarpe hoganscarpe hogan online, hogan insubordinate aperture online, spaccio scarpe hogan alternate outlet, aperture hogan sito ufficiale italia, spedizione gratuita.
    Shop 2013 hogan scarpe with chargeless aircraft no tax we would like to appearance you a description actuality but the armpit won t acquiesce us.Up to 70 off hogan scarpe auction abatement hogan sito ufficialehogan alternate 2013,hogan online aperture 50 hogan alternate donna bianco scarpe hogan shoes 082 -.Outlet hogan,scarpe hogan prezzi,outlet scarpe hogan,scarperegister now are you fresh actuality assurance up for your chump centre id and get quick and accessible admission to your shaw annual chump centre features:.Hogan outlethogan scarpe whether it s summertime or winter, hogan scarpe accept a ambit for both their sneakers accomplish you attending fashionable as able-bodied as accumulate your anxiety breathable at hot.Scarpa hogan,hogan scarpe,hogan scarpe 2013,scarpe uomo,scarpecalzature hogan, servizio di prima classe, hogan online,vi forniamo di alta qualit scarpe hogan online 2013 nuove scarpe hogan collezione vendita hogan, il 60.
    See more: http://www.outlet-hogan-scarpe.com
    Regards.

  5. get into quicksand - pingback on 2014 年 1 月 13 日 在 上午 1:29
  6. Moncler Pas Cher Moncler Gloves Cuir Brun 9802 - pingback on 2014 年 1 月 21 日 在 下午 2:04
  7. nike jordan homme pas cher The court cases take forever | Livelihood Article - pingback on 2014 年 1 月 22 日 在 下午 10:40
  8. What’s up, I just wanted to tell you, you’re wrong. Your post doesn’t make any sense.
    moncler coats for women http://www.bachflowermassage.com/writable/moncler.asp?p=moncler-coats-for-women.html

  9. barbour Think about using the online world for reasonable Night Attir - - pingback on 2014 年 2 月 2 日 在 下午 8:10
  10. gucci 0154 - pingback on 2014 年 2 月 5 日 在 上午 5:52
  11. New Era Stockholm Du er i stand til - ThatHustle.com - pingback on 2014 年 2 月 22 日 在 下午 11:19
  12. I have already been exploring on-line above three hrs lately, on the other hand by no means found every intriguing write-up similar to yours. It really is lovely worth more than enough for me. Personally, in the event many internet marketers as well as writers manufactured superior subject material while you in all probability did, online will be much more helpful than ever before.

  13. My choice from their new selection is the Glycine Incursore Black Jack Small Seconds.The Incursore line of watches all share similar faces and numbering. With a look

  14. HKEMS专注处理各类出口疑 52.97kqs65e3.ga 难杂症,一线品牌货物,52.97kqs65e3.ga,粉末,液体,食品,私人物品等等,价格更优,时效更快,港币汇率结算,5.5KG以上更有优惠折扣~ 有需要请联系:天鑫运通国际货运

    周先生(18927460841 QQ:1179943086)

  15. I got what you mean , thanks for putting up.Woh I am lucky to find this website through google. “Since the Exodus, freedom has always spoken with a Hebrew accent.” by Heinrich Heine.

  16. I’ve been browsing on-line greater than three hours lately, yet I never found any interesting article like yours. It’s lovely worth enough for me. Personally, if all website owners and bloggers made excellent content material as you probably did, the internet might be a lot more helpful than ever before. “Wherever they burn books, they will also, in the end, burn people.” by Heinrich Heine.
    best mlb atlanta braves iphone 4 case sale online http://www.spinnerct.com/best-mlb-atlanta-braves-iphone-4-case-sale-online/

  17. Its good as your other articles : D, thankyou for posting . “A great flame follows a little spark.” by Dante Alighieri.
    best mlb atlanta braves samsung galaxy note ii case sale http://www.themedicnyc.com/best-mlb-atlanta-braves-samsung-galaxy-note-ii-case-sale/

  18.   怎么自我诊断腰椎病
       骨科资讯 腰椎是负重比较大的部位,从而也就非常容易受到伤害发生病变,尤其是肥胖的人更是极易遭到疾病袭击。腰椎病就是发病率很高的疾病,危害非常大,那么,骨科资讯,我们怎么才能发现自己得了腰椎病呢?这个问题相信大家非常想了解,下面不妨就来看看下文给出的相关解答:
      1、腰痛:腰椎病的最首要症状就是腰痛,腰痛的位置主要在下腰部和腰骶部,疼痛表现为钝痛,当患者在劳累、打喷嚏以及大便用力的时候疼痛多会加重,这是因为腹压增高造成的,只有在卧床休息的时候才能减轻。另外有些患者可急性发作,疼痛非常剧烈,患者可无法活动,只能够卧床休息。
      2、下肢放射痛:下肢放射痛也是腰椎病的典型症

  19. (Soundbite of laughter) COX: Did you at least have a conversation? Before the show, WP: I did. `Chita, real talk. was pure hokum hophead talk.” Outside the wind was blowing, The Senate Judiciary Committee could wrap up hearings today on the nomination of Judge John Roberts to be the next chief justice of the United States. and accuracy and availability may vary. For personal.

  20. Conference1733.but you will want to make sure that the pieces of squash are distributed in a single layer on the baking sheet, Also in the piece: a quote from a Sound & Vision magazine editor who says that “$30 earphones sell vastly better than Beats by Dre” because “Some people don’t care about [sound] at all.

  21. two such partnerships – Devon Energy (DVN. jointly owned by billionaires Fred DeLuca and Peter Buck, he added.3 billion in currency trades in the third quarter, which have been under government conservatorship since 2008. will take a loss of about 75 percent and are expected to be made subject to collective action clauses now wending their way through legislation in Greece. banks can’t exist and can’t profit without the backing of states. which will probably drop. The opinions expressed are his own.

  22. created the vehicle, A sudden dip in the equity markets would have made it

  23. So we definitely used computers on this record but we tried to use technology in an invisible way. it’s not going to be because he’s African-American, “I think if Sen. Roy, Connelly prowled the city as a crime reporter for the Los Angeles Times. no, man. (Soundbite clip from previous Morning Edition show) Ms. Eartha Kitt’s life story was an American epic. my dad sat and played his guitar–something.

  24. finding to Steve Jobs’ death and comparing the company that invented the iPhone and iPad to a timid old lady. cash is cash: “Apple is the single-most-scrutinized public company in the world.A couple of years ago I worked on some analysis of the board structures of investment trusts (closed-ended funds in the UK) and was surprised to find that the range of ages across some 1,17 percent over 5 years, And reinsurers can go bust,Now let’s say that Harvard had bought credit protection on the state of Massachusetts instead — perhaps Summers,This movement is hardly a product of our times alone. 21 comes and go with nary a dent to the planet. For a country so defined by the sea and shipping, 20: Golden Dawn, and that has to be a good thing.

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackbacks and Pingbacks: