|
10鱼币
#include <iostream.h>
#include <winsock2.h>
#pragma comment (lib, "ws2_32.lib")
#define ICMP_ECHOREPLY 0
#define ICMP_ECHOREQ 8
#define REQ_DATASIZE 32
#define FD_SETSIZE 64
#define DESTPORT 7777
#define DESTIP "127.0.0.1"
int WaitForEchoReply(SOCKET s);
int SendEchoRequest(SOCKET s, LPSOCKADDR_IN lpstToAddr);
typedef unsigned char u_char;
typedef unsigned short u_short;
typedef unsigned int u_int;
typedef unsigned long u_long;
typedef struct tagIPHDR
{
unsigned char VIHL;
unsigned char TOS;
short TotLen;
short ID;
short FlagOff;
unsigned char TTL;
unsigned char Protocol;
unsigned short Checksum;
struct in_addr iaSrc;
struct in_addr iaDst;
}IPHDR,*PIPHDR;
typedef struct tagICMPHDR
{
u_char Type;
u_char Code;
u_short Checksum;
u_short ID;
u_short Seq;
char Data;
}ICMPHDR,*PICMPHDR;
typedef struct tagECHOREQUEST
{
ICMPHDR icmpHdr;
DWORD dwTime;
char cData[REQ_DATASIZE];
}ECHOREQUEST,*PECHOREQUEST;
typedef struct tagECHOREPLY
{
IPHDR ipHdr;
ECHOREQUEST echoRequest;
char cFiller[256];
}ECHOREPLY,*PECHOREPLY;
void main()
{
WSADATA wsaData;
int error = WSAStartup(MAKEWORD(2, 1), &wsaData);
if (error !=0)
{
cout << "wsastartup error" << endl;
return;
}
/*
SOCKET s = socket(AF_INET,SOCK_RAW,IPPROTO_ICMP);
if (s == INVALID_SOCKET)
{
cout << "Invalid socket " << endl;
WSACleanup();
return;
}
*/
SOCKET s = WSASocket (AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0,
WSA_FLAG_OVERLAPPED);
if (s == INVALID_SOCKET)
{
cout << "Invalid socket " << endl;
WSACleanup();
return;
}
struct sockaddr_in dest;
dest.sin_family = AF_INET;
dest.sin_port = htons(7777);
dest.sin_addr.s_addr = inet_addr("127.0.0.1");
for (int i=0; i<5; i++)
{
cout << sizeof(ECHOREQUEST) << endl;
int size = SendEchoRequest(s,&dest);
cout << size << endl;
cout << sizeof(ICMPHDR) << endl;
int nRet = WaitForEchoReply(s);
cout << nRet << endl;
}
}
int SendEchoRequest(SOCKET s, LPSOCKADDR_IN lpstToAddr)
{
static ECHOREQUEST echoReq;
static nId=1;
static nSeq =1;
int nRet1;
echoReq.icmpHdr.Type=ICMP_ECHOREQ;
echoReq.icmpHdr.Code=0;
echoReq.icmpHdr.Checksum=0;
echoReq.icmpHdr.ID=nId++;
echoReq.icmpHdr.Seq=nSeq++;
for(nRet1=0;nRet1<REQ_DATASIZE;nRet1++)
echoReq.cData[nRet1]=' '+nRet1;
echoReq.dwTime=GetTickCount();
nRet1=sendto(s,
(LPSTR)&echoReq,
sizeof(ECHOREQUEST),
0,
(SOCKADDR*)lpstToAddr,
sizeof(SOCKADDR_IN));
if(nRet1==SOCKET_ERROR)
cout << "sendto() error" << endl;
return nRet1;
}
int WaitForEchoReply(SOCKET s)
{
struct timeval Timeout;
fd_set readfds;
Timeout.tv_sec=1;
Timeout.tv_usec=0;
FD_ZERO(&readfds);
FD_SET(s,&readfds);
return select(1,&readfds,NULL,NULL,&Timeout);
}
|
|