用原始套接字监听局域网内的数据包
源代码在线查看: 用原始套接字监听局域网内的数据包,解析ip头内的目的ip出现问题.txt
用原始套接字监听局域网内的数据包,解析IP头内的目的IP出现问题
用原始套接字监听局域网内的数据包,为什么只能得到ip头内的源IP地址而目的IP地址总是会等于源IP地址??
奇怪了为什么就是不能得到目的IP地址??
#include "stdafx.h"
#include ;
#include ;
#include ;
#include ;
#pragma comment(lib,"Ws2_32")
#define MAX_PACK_LEN 1024
typedef struct ip_hdr //定义IP首部
{
unsigned char h_lenver; //4位首部长度,4位IP版本号
unsigned char tos; //8位服务类型TOS
unsigned short total_len; //16位总长度(字节)
unsigned short ident; //16位标识
unsigned short th_flag; //3位标志位
unsigned char ttl; //8位生存时间 TTL
unsigned char iProtocol; //8位协议 (TCP, UDP 或其他)
unsigned short checksum; //16位IP首部校验和
unsigned int sourceIP; //32位源IP地址
unsigned int destIP; //32位目的IP地址
}IP_HEADER;
void DeCodeIP(char *buf,int iBufSize) //解析侦听到的IP数据包
{
IP_HEADER * pIPhdr;
pIPhdr=(IP_HEADER * )buf;
sockaddr_in dest,src;
dest.sin_family=AF_INET;
dest.sin_addr.S_un.S_addr=pIPhdr->;destIP;
src.sin_family=AF_INET;
src.sin_addr.S_un.S_addr=pIPhdr->;sourceIP;
char *lpdest=inet_ntoa(dest.sin_addr);
char *lpsrc=inet_ntoa(src.sin_addr);
printf("dest:%s,src:%s\n",lpdest,lpsrc);
}
int main(int argc, char* argv[])
{
int iErrorCode;
char RecvBuf[MAX_PACK_LEN];
WSADATA wsaData;
iErrorCode = WSAStartup(MAKEWORD(2,2),&wsaData);
SOCKET SockRaw = WSASocket(AF_INET, SOCK_RAW, IPPROTO_IP, NULL, 0, WSA_FLAG_OVERLAPPED);
SOCKADDR_IN sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(6000);
sa.sin_addr.S_un.S_addr=inet_addr("192.168.0.1");
if(bind(SockRaw, (PSOCKADDR)&sa, sizeof(sa))!=0)
{
printf("bind error!");
WSACleanup();
}
DWORD dwBufferLen[10] ;
DWORD dwBufferInLen=1;
DWORD dwBytesReturned=0;
iErrorCode=WSAIoctl(SockRaw, SIO_RCVALL,&dwBufferInLen, sizeof(dwBufferInLen),
NULL, 0,&dwBytesReturned , NULL , NULL );//设置网卡为混杂模式以监听流过网卡的数据包
if(iErrorCode==SOCKET_ERROR)
{
printf("ioctl error!");
WSACleanup();
}
while(1)
{
memset(RecvBuf, 0, sizeof(RecvBuf));
iErrorCode = recv(SockRaw, RecvBuf, sizeof(RecvBuf),0);
if(iErrorCode!=SOCKET_ERROR&&iErrorCode>;20)
DeCodeIP(RecvBuf, iErrorCode);
}
return 0;
}