123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- // 必要的头文件和lib;
- #include <Winsock2.h>
- #include <iphlpapi.h>
- #include <icmpapi.h>
- #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;
- }
|