自己写的Ping 程序

来源:互联网 发布:江湖商圈o2o源码下载 编辑:程序博客网 时间:2024/05/26 02:53
// MyPingConsole.cpp : Defines the entry point for the console application.//#include "stdafx.h"#pragma comment(lib,"ws2_32.lib")#include <winsock2.h>#include <ws2tcpip.h>#include <stdio.h>#include <stdlib.h>#define IP_RECORD_ROUTE  0x7// // IP header structure//typedef struct _iphdr {unsigned int   h_len:4;        // Length of the headerunsigned int   version:4;      // Version of IPunsigned char  tos;            // Type of serviceunsigned short total_len;      // Total length of the packetunsigned short ident;          // Unique identifierunsigned short frag_and_flags; // Flagsunsigned char  ttl;            // Time to liveunsigned char  proto;          // Protocol (TCP, UDP etc)unsigned short checksum;       // IP checksumunsigned int   sourceIP;unsigned int   destIP;} IpHeader;#define ICMP_ECHO        8#define ICMP_ECHOREPLY   0#define ICMP_MIN         8 // Minimum 8-byte ICMP packet (header)//// ICMP header structure//typedef struct _icmphdr {BYTE   i_type;BYTE   i_code;                 // Type sub codeUSHORT i_cksum;USHORT i_id;USHORT i_seq;// This is not the standard header, but we reserve space for timeULONG  timestamp;} IcmpHeader;//// IP option header - use with socket option IP_OPTIONS//typedef struct _ipoptionhdr{unsigned char        code;        // Option typeunsigned char        len;         // Length of option hdrunsigned char        ptr;         // Offset into optionsunsigned long        addr[9];     // List of IP addrs} IpOptionHeader;#define DEF_PACKET_SIZE  32        // Default packet size#define MAX_PACKET       1024      // Max ICMP packet size#define MAX_IP_HDR_SIZE  60        // Max IP header size w/optionsBOOL  bRecordRoute;int   datasize;char *lpdest;//// Function: usage//// Description://    Print usage information//void usage(char *progname){printf("usage: ping -r <host> [data size] ");printf("       -r           record route ");printf("        host        remote machine to ping ");printf("        datasize    can be up to 1KB ");ExitProcess(-1);}// // Function: FillICMPData//// Description://    Helper function to fill in various fields for our ICMP request//void FillICMPData(char *icmp_data, int datasize){IcmpHeader *icmp_hdr = NULL;char       *datapart = NULL;icmp_hdr = (IcmpHeader*)icmp_data;icmp_hdr->i_type = ICMP_ECHO;        // Request an ICMP echoicmp_hdr->i_code = 0;icmp_hdr->i_id = (USHORT)GetCurrentProcessId();icmp_hdr->i_cksum = 0;icmp_hdr->i_seq = 0;datapart = icmp_data + sizeof(IcmpHeader);//// Place some junk in the buffer//memset(datapart, 'E' , datasize - sizeof(IcmpHeader));}// // Function: checksum//// Description://    This function calculates the 16-bit one s complement sum//    of the supplied buffer (ICMP) header//USHORT checksum(USHORT *buffer, int size) {unsigned long cksum=0;while (size > 1) {cksum += *buffer++;size -= sizeof(USHORT);}if (size) {cksum += *(UCHAR*)buffer;}cksum = (cksum >> 16) + (cksum & 0xffff);cksum += (cksum >>16);return (USHORT)(~cksum);}//// Function: DecodeIPOptions//// Description://    If the IP option header is present, find the IP options//    within the IP header and print the record route option//    values//void DecodeIPOptions(char *buf, int bytes){IpOptionHeader *ipopt = NULL;IN_ADDR         inaddr;int             i;HOSTENT        *host = NULL;ipopt = (IpOptionHeader *)(buf + 20);printf("RR:   ");for(i = 0; i < (ipopt->ptr / 4) - 1; i++){inaddr.S_un.S_addr = ipopt->addr[i];if (i != 0)printf("      ");host = gethostbyaddr((char *)&inaddr.S_un.S_addr,sizeof(inaddr.S_un.S_addr), AF_INET);if (host)printf("(%-15s) %s ", inet_ntoa(inaddr), host->h_name);elseprintf("(%-15s) ", inet_ntoa(inaddr));}return;}//// Function: DecodeICMPHeader//// Description://    The response is an IP packet. We must decode the IP header to//    locate the ICMP data.//void DecodeICMPHeader(char *buf, int bytes, struct sockaddr_in *from){IpHeader       *iphdr = NULL;IcmpHeader     *icmphdr = NULL;unsigned short  iphdrlen;DWORD           tick;static   int    icmpcount = 0;iphdr = (IpHeader *)buf;// Number of 32-bit words * 4 = bytesiphdrlen = iphdr->h_len * 4;tick = GetTickCount();if ((iphdrlen == MAX_IP_HDR_SIZE) && (!icmpcount))DecodeIPOptions(buf, bytes);if (bytes  < iphdrlen + ICMP_MIN) {printf("Too few bytes from %s ", inet_ntoa(from->sin_addr));return;}icmphdr = (IcmpHeader*)(buf + iphdrlen);if (icmphdr->i_type != ICMP_ECHOREPLY) {printf("nonecho type %d recvd ", icmphdr->i_type);return;}// Make sure this is an ICMP reply to something we sent!if (icmphdr->i_id != (USHORT)GetCurrentProcessId()) {printf("someone else s packet! ");return ;}printf("%d bytes from %s:\n", bytes, inet_ntoa(from->sin_addr));printf(" icmp_seq = %d.\n", icmphdr->i_seq);printf(" time: %d ms\n", tick - icmphdr->timestamp);printf(" ");    char *pData=(buf + iphdrlen +sizeof(IcmpHeader));char szData[204] ={0};int nLen = buf + bytes - pData;if(nLen>200)nLen = 200;memcpy(szData,pData,nLen);printf("Data is %s\n",szData);icmpcount++;return;}void ValidateArgs(int argc, char **argv){int      i;bRecordRoute = FALSE;lpdest = NULL;datasize = DEF_PACKET_SIZE;for(i = 1; i < argc; i++){if ((argv[i][0] ==  '-' ) || (argv[i][0] ==  '/' )){switch (tolower(argv[i][1])){case  'r' :        // Record route optionbRecordRoute = TRUE;break;default:usage(argv[0]);break;}}lpdest = argv[i];}}//// Function: main//// Description://    Setup the ICMP raw socket, and create the ICMP header. Add//    the appropriate IP option header, and start sending ICMP//    echo requests to the endpoint. For each send and receive,//    we set a timeout value so that we don t wait forever for a //    response in case the endpoint is not responding. When we//    receive a packet decode it.//int main(int argc, char **argv){WSADATA            wsaData;SOCKET             sockRaw = INVALID_SOCKET;struct sockaddr_in dest,from;int                nRecvBytes,fromlen = sizeof(from),nTimeOut = 2000,ret;char              *pICMPData = NULL,*pRecvBuf = NULL;unsigned int       addr = 0;USHORT             seq_no = 0;struct hostent     *hp = NULL;IpOptionHeader     ipopt;if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0){printf("WSAStartup() failed: %d ", GetLastError());return -1;}ValidateArgs(argc, argv);//// WSA_FLAG_OVERLAPPED flag is required for SO_RCVTIMEO, // SO_SNDTIMEO option. If NULL is used as last param for // WSASocket, all I/O on the socket is synchronous, the // internal user mode wait code never gets a chance to // execute, and therefore kernel-mode I/O blocks forever. // A socket created via the socket function has the over-// lapped I/O attribute set internally. But here we need // to use WSASocket to specify a raw socket.//// If you want to use timeout with a synchronous // nonoverlapped socket created by WSASocket with last // param set to NULL, you can set the timeout by using // the select function, or you can use WSAEventSelect and // set the timeout in the WSAWaitForMultipleEvents // function.//sockRaw = WSASocket (AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0,WSA_FLAG_OVERLAPPED);if (sockRaw == INVALID_SOCKET) {printf("WSASocket() failed: %d ", WSAGetLastError());return -1;}// Set the send/recv timeout valuesnRecvBytes = setsockopt(sockRaw, SOL_SOCKET, SO_RCVTIMEO, (char*)&nTimeOut, sizeof(nTimeOut));if(nRecvBytes == SOCKET_ERROR) {printf("setsockopt(SO_RCVTIMEO) failed: %d ", WSAGetLastError());return -1;}nRecvBytes = setsockopt(sockRaw, SOL_SOCKET, SO_SNDTIMEO, (char*)&nTimeOut, sizeof(nTimeOut));if (nRecvBytes == SOCKET_ERROR) {printf("setsockopt(SO_SNDTIMEO) failed: %d ", WSAGetLastError());return -1;}memset(&dest, 0, sizeof(dest));//// Resolve the endpoint s name if necessary//dest.sin_family = AF_INET;if ((dest.sin_addr.s_addr = inet_addr(lpdest)) == INADDR_NONE){if ((hp = gethostbyname(lpdest)) != NULL){memcpy(&(dest.sin_addr), hp->h_addr, hp->h_length);dest.sin_family = hp->h_addrtype;printf("dest.sin_addr = %s \n", inet_ntoa(dest.sin_addr));}else{printf("gethostbyname() failed: %d ",WSAGetLastError());return -1;}}        // // Create the ICMP packet//       datasize += sizeof(IcmpHeader);  pICMPData = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,MAX_PACKET);pRecvBuf = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,MAX_PACKET);if (!pICMPData) {printf("HeapAlloc() failed: %d\n", GetLastError());return -1;}memset(pICMPData,0,MAX_PACKET);FillICMPData(pICMPData,datasize);//// Start sending/receiving ICMP packets//while(1) {static int nCount = 0;int        nRecvBytes =0;if (nCount++ == 4) break;((IcmpHeader*)pICMPData)->i_cksum = 0;((IcmpHeader*)pICMPData)->timestamp = GetTickCount();((IcmpHeader*)pICMPData)->i_seq = seq_no++;((IcmpHeader*)pICMPData)->i_cksum = checksum((USHORT*)pICMPData, datasize);nRecvBytes = sendto(sockRaw, pICMPData, datasize, 0, (struct sockaddr*)&dest, sizeof(dest));if (nRecvBytes == SOCKET_ERROR){if (WSAGetLastError() == WSAETIMEDOUT) {printf("timed out ");continue;}printf("sendto() failed: %d \n", WSAGetLastError());return -1;}if (nRecvBytes < datasize) {printf("Wrote %d bytes \n", nRecvBytes);}nRecvBytes = recvfrom(sockRaw, pRecvBuf, MAX_PACKET, 0, (struct sockaddr*)&from, &fromlen);if (nRecvBytes == SOCKET_ERROR){if (WSAGetLastError() == WSAETIMEDOUT) {printf("timed out ");continue;}printf("recvfrom() failed: %d \n", WSAGetLastError());return -1;}DecodeICMPHeader(pRecvBuf, nRecvBytes, &from);Sleep(1000);}if (sockRaw != INVALID_SOCKET) closesocket(sockRaw);HeapFree(GetProcessHeap(), 0, pRecvBuf);HeapFree(GetProcessHeap(), 0, pICMPData);WSACleanup();return 0;}

0 0
原创粉丝点击