路由跟蹤技術

用來肯定路由器的IP地址,也就是在網絡上到達特定主機所通過的計算機。網絡

程序須要兩個套接字:socket

1 一個用於接收ICMP封包的原始套接字sRawspa

2 用於發送TTL不斷增長UDP封包的套接字sSend。code

實現代碼以下:blog

void main() { char *szDestIp = "10.16.115.178"; // 210.181.18.12910.16.115.25 61.55.66.30

    char recvBuf[1024] = { 0 }; // 建立用於接收ICMP封包的原始套節字,綁定到本地端口
    SOCKET sRaw = ::socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); sockaddr_in in; in.sin_family = AF_INET; in.sin_port = 0; in.sin_addr.S_un.S_addr = INADDR_ANY; if(::bind(sRaw, (sockaddr*)&in, sizeof(in)) == SOCKET_ERROR) { printf(" bind() failed \n"); return; } SetTimeout(sRaw, 5*1000); // 建立用於發送UDP封包的套節字
    SOCKET sSend = ::socket(AF_INET, SOCK_DGRAM, 0); SOCKADDR_IN destAddr; destAddr.sin_family = AF_INET; destAddr.sin_port = ::htons(22); destAddr.sin_addr.S_un.S_addr = ::inet_addr(szDestIp); int nTTL = 1; int nRet; ICMP_HDR *pICMPHdr; int nTick; SOCKADDR_IN recvAddr; do { // 設置UDP封包的TTL值
 SetTTL(sSend, nTTL); nTick = ::GetTickCount(); // 發送這個UDP封包
        nRet = ::sendto(sSend, "hello", 5, 0, (sockaddr*)&destAddr, sizeof(destAddr)); if(nRet == SOCKET_ERROR) { printf(" sendto() failed \n"); break; } // 等待接收路由器返回的ICMP報文
        int nLen = sizeof(recvAddr); nRet = ::recvfrom(sRaw, recvBuf, 1024, 0, (sockaddr*)&recvAddr, &nLen); if(nRet == SOCKET_ERROR) { if(::WSAGetLastError() == WSAETIMEDOUT) { printf(" time out \n"); break; } else { printf(" recvfrom() failed \n"); break; } } // 解析接收到的ICMP數據
        pICMPHdr = (ICMP_HDR*)&recvBuf[20]; // sizeof(IPHeader)

        if(pICMPHdr->icmp_type != 11 && pICMPHdr->icmp_type != 3 && pICMPHdr->icmp_code != 3) { printf(" Unexpected Type: %d , code: %d \n", pICMPHdr->icmp_type, pICMPHdr->icmp_code); } else { char *szIP = ::inet_ntoa(recvAddr.sin_addr); printf(" 第%d個路由器,IP地址:%s \n", nTTL, szIP); printf(" 用時:%d毫秒 \n", ::GetTickCount() - nTick); } if(destAddr.sin_addr.S_un.S_addr == recvAddr.sin_addr.S_un.S_addr) { printf("目標可達 \n"); break; } printf("//------------------------------------// \n"); }while(nTTL++ < 20); ::closesocket(sRaw); ::closesocket(sSend); }
相關文章
相關標籤/搜索