// 必要的头文件和lib; #include #include #include #pragma comment(lib,"Iphlpapi.lib") #pragma comment(lib,"Ws2_32.lib") bool ping(LPCSTR lpIPAddress) { bool bresult = false; if (lpIPAddress == NULL ) return bresult; HANDLE hIcmpFile; unsigned long ipaddr = INADDR_NONE; DWORD dwRetVal = 0; char SendData[] = "Data Buffer"; LPVOID ReplyBuffer = NULL; DWORD ReplySize = 0; if(lpIPAddress[0] >= '0' && lpIPAddress[0] <= '9') {//4段十进制; ipaddr = inet_addr(lpIPAddress); if(ipaddr == INADDR_NONE) {// 地址无效; return false; } } else {//计算机名; // 初始化socket; WSADATA WSAData = { 0 }; if(0 != WSAStartup(MAKEWORD(2, 2), &WSAData)) return false; // gethostbyname前必须WSAStartup; hostent *phostent = gethostbyname(lpIPAddress); if(phostent == NULL) return false; ipaddr = *(DWORD*)phostent->h_addr_list[0]; } // 创建imcp协议句柄; hIcmpFile = IcmpCreateFile(); if (hIcmpFile == INVALID_HANDLE_VALUE) return bresult; ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData); ReplyBuffer = (VOID*) malloc(ReplySize); if (ReplyBuffer == NULL) return bresult; // 发送数据; dwRetVal = IcmpSendEcho(hIcmpFile, ipaddr, SendData, sizeof(SendData), NULL, ReplyBuffer, ReplySize, 1000); if (dwRetVal != 0) { PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)ReplyBuffer; if ( pEchoReply->Status == 0 ) { bresult = true; } } if (ReplyBuffer) free(ReplyBuffer); return bresult; } bool telnet(IN LPCCH lpIPAddress, IN DWORD dwPort) { // 初始化socket; WSADATA WSAData = { 0 }; if(0 != WSAStartup(MAKEWORD(2, 2), &WSAData)) return false; // 创建客户端; SOCKET sock; SOCKADDR_IN srvaddr; sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sock == INVALID_SOCKET) {// 创建套接字失败; WSACleanup(); return false; } // 填充address; if(lpIPAddress[0] >= '0' && lpIPAddress[0] <= '9') {//4段十进制; srvaddr.sin_addr.S_un.S_addr = inet_addr(lpIPAddress); if(srvaddr.sin_addr.S_un.S_addr == INADDR_NONE) {// 地址无效; closesocket(sock); WSACleanup(); return false; } } else {//计算机名; hostent *phostent = gethostbyname(lpIPAddress); if(phostent == NULL) { closesocket(sock); WSACleanup(); return false; } srvaddr.sin_addr.S_un.S_addr = *(DWORD*)phostent->h_addr_list[0]; } srvaddr.sin_port = htons(dwPort); srvaddr.sin_family = AF_INET; // 连接服务器; if( SOCKET_ERROR == connect(sock, (sockaddr*)&srvaddr, sizeof(SOCKADDR_IN)) ) {// 连接失败,认为telnet失败; closesocket(sock); WSACleanup(); return false; } // 释放资源; closesocket(sock); WSACleanup(); return true; }