资源描述:
《ping应用程序实现代码》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Ping应用程序实现代码#include#include#include#include#include"winsock.h"#pragmacomment(lib,"Ws2_32");#defineSEND_SIZE32#definePACKET_SIZE4096#defineICMP_ECHO8#defineICMP_ECHOREPLY0structicmp{unsignedcharicmp_type;unsignedcharicmp_code;unsignedshorticmp_cksum;unsign
2、edshorticmp_id;unsignedshorticmp_seq;unsignedlongicmp_data;};structip{unsignedcharip_hl:4;unsignedcharip_v:4;unsignedcharip_tos;unsignedshortip_len;unsignedshortip_id;unsignedshortip_off;unsignedcharip_ttl;unsignedcharip_p;unsignedshortip_sum;unsignedlongip_src;unsignedlongip_dst;};unsignedcharse
3、ndpacket[PACKET_SIZE];unsignedcharrecvpacket[PACKET_SIZE];structsockaddr_indest_addr;structsockaddr_infrom_addr;intsockfd;intpid;unsignedshortcal_chksum(unsignedshort*addr,intlen);intpack(intpack_no);intunpack(unsignedchar*buf,intlen);voidsend_packet(void);voidrecv_packet(void);voidmain(){intargc
4、;char*argv[2];argc=2;argv[0]="-t";argv[1]="192.168.1.2";structhostent*host;structprotoent*protocol;WSADATAwsaData;inttimeout=1000;intSEND_COUNT=4;inti;char*par_host;par_host=argv[argc-1];//IP??Öµswitch(argc){case2:break;case3:if(strcmp(argv[1],"-t")==0){SEND_COUNT=10000;break;}//fallthroughdefaul
5、t:printf("usage:%s[-t]HostnameorIPaddress",argv[0]);exit(1);}if(WSAStartup(0x1010,&wsaData)!=0){printf("wsastartuperror");exit(1);}if((protocol=getprotobyname("icmp"))==NULL){printf("getprotobynameerror");exit(1);}printf("%s",protocol->p_name);printf("%s",protocol->p_aliases);printf("%d
6、",protocol->p_proto);system("pause");if((sockfd=socket(AF_INET,SOCK_RAW,protocol->p_proto))<0){printf("socketerror");exit(1);}if(setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,sizeof(timeout))<0)fprintf(stderr,"failedtosetrecvtimeout:%d",WSAGetLastError());if(setsockopt(sockfd,SOL
7、_SOCKET,SO_SNDTIMEO,(char*)&timeout,sizeof(timeout))<0)fprintf(stderr,"failedtosetsendtimeout:%d",WSAGetLastError());memset(&dest_addr,0,sizeof(dest_addr));dest_addr.sin_family=AF_INET;printf("%s",par_host);if(host