利用 rawsocket 抓包
by adie
2015-08-27 17:03:59
- #include <stdio.h>
- #include <winsock2.h>
- #include <mstcpip.h>
-
- void analyse_package(char* buff, int length)
- {
- struct _iphdr
- {
- unsigned char h_verlen;
- unsigned char tos;
- unsigned short total_len;
- unsigned short ident;
- unsigned short frag_and_flags;
- unsigned char ttl;
- unsigned char proto;
- unsigned short checksum;
- unsigned int sourceIP;
- unsigned int destIP;
- };
-
- _iphdr* pIPHeader = (_iphdr*)(buff);
-
-
-
-
-
-
-
-
-
-
-
- printf("recv a packet len = %d\n", length);
- }
-
- int main(int argc, char **argv)
- {
- WSADATA wsaData = { 0 };
- int nRet = WSAStartup(MAKEWORD(2, 1), &wsaData);
-
- SOCKET snifferSocket = socket(AF_INET , SOCK_RAW , IPPROTO_IP);
- if(snifferSocket == INVALID_SOCKET)
- {
- printf("Create Raw Sniffer Socket Error: %d\r\n", WSAGetLastError());
- return 0;
- }
-
- sockaddr_in localaddr;
- memset(&localaddr, 0, sizeof(localaddr));
-
- localaddr.sin_family = AF_INET;
- localaddr.sin_port = htons(0);
-
- char hostname[255];
- if(gethostname(hostname, 255) != 0)
- {
- printf("Gethostname Error: %d\r\n", WSAGetLastError());
- return 0;
- }
-
- hostent * pHostent = gethostbyname(hostname);
- memcpy(&localaddr.sin_addr.S_un.S_addr,pHostent->h_addr_list[0],pHostent->h_length);
-
- if(bind(snifferSocket, (SOCKADDR*)&localaddr, sizeof(localaddr)))
- {
- printf("Bind Error: %d\r\n", WSAGetLastError());
- return false;
- }
-
- DWORD dwBufferLen[10] = { 0 } ;
- DWORD dwBufferInLen = 1 ;
- DWORD dwBytesReturned = 0 ;
- if(WSAIoctl(snifferSocket, SIO_RCVALL, &dwBufferInLen,
- sizeof(dwBufferInLen),
- &dwBufferLen,
- sizeof(dwBufferLen),
- &dwBytesReturned
- ,NULL, NULL) != 0)
- {
- printf("WSAIoctl Error: %d\r\n", WSAGetLastError());
- return 0;
- }
-
- printf("Sniffer Socket inited.\r\n");
-
- static const int MAX_PACK_LEN = 65535;
- static char recvBuffer[MAX_PACK_LEN] = { 0 };
-
- while(1)
- {
- int packLen = recv(snifferSocket, recvBuffer, sizeof(recvBuffer), 0);
-
- if(packLen == 0)
- {
- printf("sniffer socket has been closed\r\n");
- }
- else if(packLen == SOCKET_ERROR)
- {
- printf("Recv Error: %d\r\n", WSAGetLastError());
- }
- else
- {
- analyse_package(recvBuffer, packLen);
- }
- }
-
- return 0;
- }
▲评论