设置网卡混杂模式

时间:2022-11-03 15:14:29

关键API :ioctlsocket()

设置杂收模式 宏  #define SIO_RCVALL  (0x80000000 | (0x18000000) | (1))

IP头:

typedef struct _IPHeader
{                        //IP数据包头
 BYTE Ver_HLen;        //版本+报头长度
 BYTE TOS;            //服务类型
 WORD TotalLen;        //总长度
 WORD ID;            //标识
 WORD Flag_Segment;    //标志+片偏移
 BYTE TTL;            //生存周期
 BYTE Protocol;        //协议类型
 WORD Checksum;        //头部校验和
 in_addr  SrcIP;        //源IP地址
 in_addr DstIP;        //目的IP地址
} IPHEADER;

 

TCP头:

typedef struct _TCPHEADER
{
  unsigned short srcPort;//2个字节
  unsigned short DestPort;//2个字节
  unsigned int   sequeceNo; //4 个字节 序号
  unsigned int   acAnswerNo; //4字节
  unsigned char  dataoffset;//布首长度
  unsigned char  flage;
  unsigned short windows;
  unsigned short checksum;
  unsigned short urgentPointer;
}TCPHEADER;

 

流程 --》 创建socket --》bind 本地地址-》ioctlsocket()设置杂收模式---》recv 接收数据

 

unsigned int  sinfferClass::_Run(LPVOID lpramra)
{
SOCKET s=socket(AF_INET,SOCK_RAW,IPPROTO_IP);
int nRet=WSAGetLastError();
sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(0);
sin.sin_addr.S_un.S_addr=inet_addr("192.168.0.100");
::bind(s,(sockaddr *)&sin,sizeof(sin));
nRet=WSAGetLastError();
DWORD dwValue=1;
ioctlsocket(s,SIO_RCVALL,&dwValue);
nRet=WSAGetLastError();
char * pbuffer=new char[1024];
IPHEADER ip;
TCPHEADER tcp;
int nIPLen=sizeof(IPHEADER);
int nTcpLen=sizeof(TCPHEADER);
while(1)
{
memset(pbuffer,0,1024);
nRet=recv(s,pbuffer,1024,0);
int destPort=0;

if (nRet>0)
{
memcpy(&ip,pbuffer,nIPLen);
pbuffer=pbuffer+nIPLen;
memcpy(&tcp,pbuffer,nTcpLen);
destPort=ntohs(tcp.DestPort);
TRACE(inet_ntoa(ip.SrcIP));
TRACE("----->");
TRACE(inet_ntoa(ip.DstIP));
memmove(pbuffer,pbuffer+20,nRet-40);
}

}
return true;
}

 大概就是这样,代码肯定有一点小bug 请大家批评指正