//初试化RAW Socket, 设置ttl, 初试化dest
// 返回值 <0 表失败
int setup_for_ping(char* host, int ttl, SOCKET& sd, sockaddr_in& dest)
{
// Create the socket
sd = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, 0, 0, 0);
if (sd == INVALID_SOCKET) {
cerr << "Failed to create raw socket: " << WSAGetLastError() <<
endl;
return -1;
}
if (setsockopt(sd, IPPROTO_IP, IP_TTL, (const char*)&ttl,
sizeof(ttl)) == SOCKET_ERROR) {
cerr << "TTL setsockopt failed: " << WSAGetLastError() << endl;
return -1;
}
// Initialize the destination host info block
memset(&dest, 0, sizeof(dest));
// Turn first passed parameter into an IP address to ping
unsigned int addr = inet_addr(host);
if (addr != INADDR_NONE) {
// It was a dotted quad number, so save result
dest.sin_addr.s_addr = addr;
dest.sin_family = AF_INET;
}
else {
// Not in dotted quad form, so try and look it up
hostent* hp = gethostbyname(host);
if (hp != 0) {
// Found an address for that host, so save it
memcpy(&(dest.sin_addr), hp->h_addr, hp->h_length);
dest.sin_family = hp->h_addrtype;
}
else {
// Not a recognized hostname either!
cerr << "Failed to resolve " << host << endl;
return -1;
}
}
return 0;
}