📄 sniffer.c
字号:
/*下面是包含进行调用系统和网络函数的头函数]*/
#include <winsock2.h>
#include "winuser.h"
#include <string.h>
#include <winsock2.h>
#include "stdio.h"
#pragma comment(lib, "ws2_32")
#include <stdlib.h>
#include <windows.h>
//#include<netinet/in.h>
//#include<arpa/iner.h>
/*下面是IP和TCP包头结构*/
struct ip{
unsigned int ip_length:4; /*定义IP头的长度*/
unsigned int ip_vertion:4; /*IP版本,Ipv4*/
unsigned char ip_tos; /*服务类型*/
unsigned short ip_total_length;/*IP数据包的总长度*/
unsigned short ip_id; /*鉴定域*/
unsigned short ip_flags; /*IP标志*/
unsigned char ip_ttl; /*IP包的存活期*/
unsigned char ip_protocol; /*IP上层的协议 */
unsigned short ip_cksum; /*IP头的校验和*/
unsigned int ip_source; /*源IP地址*/
unsigned int ip_dest; /*目的IP地址*/
};
struct tcp{
unsigned short tcp_source_port; /*定义TCP段口号*/
unsigned short tcp_dest_port; /*TCP目的端口*/
unsigned int tcp_seqno; /*TCP序列号*/
unsigned int tcp_ackno; /*发送者期望的下一个序列号*/
/*下面几个是TCP标志*/
unsigned int tcp_res1:4,
tcp_hlen:4,
tcp_fin:4,
tcp_syn:1,
tcp_rst:1,
tcp_psh:1,
tcp_ack:1,
tcp_urg:1,
tcp_res2:2;
unsigned short tcp_winsizet; /*能接收的最大字节数*/
unsigned short tcp_cksumt; /*TCP校验和*/
unsigned short tcp_urgentt; /*紧急事件标志*/
};
/*主函数*/
int main()
{
int sock,bytes_received,kfromlen;
char buffer[65535];
struct sockaddr_in from; /*定义socket结构*/
struct ip *ip; /*定义IP和TCP结构*/
struct tcp *tcp;
sock=socket(AF_INET,SOCK_RAW,IPPROTO_TCP);
/*上面是建立socket连接,第一个参数是地址族类型,用INTERNET类型*/
/*第二个参数是socket类型,这里涌了SOCK_RAW,它可以绕过传输曾*/
/*直接访问IP层的包,为了调用SOCKET_RAW,,需要有root权限*/
/*第三个参数是协议,选IPPROTO_TCP指定了接收TCP层的内容*/
while(1) /*建立一个死循环,不停的接收网络信息*/
{
kfromlen=sizeof from;
bytes_received=recvfrom(sock,
buffer,sizeof buffer,
0,
(struct sockaddr*)&from,
&kfromlen);
/*上面这个函数是从建立的socket连接中接受数据*/
/*因为recvfrom()需要一个sockaddr数据类型,所以我们用了一个强制类型转换*/
printf("\nBytes received :::%sd\n",bytes_received); /*显示出接收的数据字节数*/
printf("Source address ::: %s\n:",ip->ip_length); /*显示出源地址*/
ip=(struct ip*)buffer; /*把接收的数据转化成我们须先定义的结构,便于查找*/
printf("IP header length ::: %d\n",ip->ip_length); /*显示IP头的长度*/
printf("Protlcol ::: %d\n",ip->ip_protocol); /*显示协议类型,6是TCP,17是UDP*/
tcp=(struct tcp*)(buffer+(4*ip->ip_length));
/*上面这句需要详细解释一下,因为接收到的包头数据中,IP头的大小是固定的4字节*/
/*所以我们用IP长度乘以4,指向TCP头部分*/
printf("Source port ::: %d\n",ntohs(tcp->tcp_source_port)); /*显示出源端口*/
printf("Destport ::: %d\n",ntohs(tcp->tcp_dest_port)); /*显示出目标端口*/
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -