2

我想在 Windows 中用套接字制作一个简单的网络嗅探器。这是我的大学项目。如何嗅探所有端口?这是错的吗?我的项目运行时出现任何错误但无法正常工作。我想嗅探所有数据包,但这段代码只嗅探一个端口。

#pragma comment(lib, "ws2_32.lib")

#include <winsock2.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <time.h>
#include <iostream>
using namespace std;

#pragma pack(push, 1)
struct iphdr {
    unsigned char ihl:4;
    unsigned char ver:4;

    unsigned char tos;
    unsigned short totlen;
    unsigned short id;
    unsigned short frag_and_flags;
    unsigned char ttl;
    unsigned char proto;
    unsigned short checksum;
    unsigned int src;
    unsigned int dst;
};


#pragma pack(pop)

#define HOSTNAME_LEN 1024
#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1)
#define PAKSIZE 65536
SOCKET s0k;
short promiscuous=1;
int minSize = 30;
bool init_net() 
{

    WSADATA w;
    SOCKADDR_IN sa;
    DWORD bytes;
    char hostname[HOSTNAME_LEN];
    struct hostent *h;
    unsigned int opt = 1;

    if (WSAStartup(MAKEWORD(2,2), &w) != 0)
    {
        return false;
    }

    if ((s0k = socket(AF_INET, SOCK_RAW, IPPROTO_IP)) == INVALID_SOCKET)
    {
        return false;
    }

    if ((gethostname(hostname, HOSTNAME_LEN)) == SOCKET_ERROR)
    {
        return false;
    }

    if ((h = gethostbyname(hostname)) == NULL)
    {
        return false;
    }

    sa.sin_family = AF_INET;
    sa.sin_port = htons(80);
    memcpy(&sa.sin_addr.S_un.S_addr, h->h_addr_list[0], h->h_length);
    if ((bind(s0k, (SOCKADDR *)&sa, sizeof(sa))) == SOCKET_ERROR)
    {
        return false;
    }

}

bool process_pak(char *pak, int len) 
{
    struct iphdr *ip;
    char *data;
    unsigned char proto;
    int i, j, k, end, datasize;
    ip = (struct iphdr *) pak;
    struct in_addr addr;
    addr.s_addr = ip->src;
    char *dot_ip = inet_ntoa(addr);
    char ipp[] = "192.168.1.1";
    char ippp[sizeof(ipp)]={0};
    strcpy(ippp,dot_ip);
    if(*ippp == *ipp)
    {
        return true;
    } 
    else
    {
        return false;
    }
}
int main() 
{
    char pak[PAKSIZE];
    DWORD bytes;
    init_net();
    bool wh=false;
    while(wh == false)
    {
        memset(pak, 0, sizeof(pak));
        if ((bytes = recv(s0k, pak, sizeof(pak), 0)) != SOCKET_ERROR)
        {
            process_pak(pak, bytes);
            wh=true;
        }
    }
}
4

0 回答 0