raw socket

/**/
#include 
#include 
#include 
#include 
#include 
#include 
typedef struct _iphdr 			//定义IP首部 
{ 
    unsigned char h_verlen; 		//4位首部长度+4位IP版本号 
    unsigned char tos; 			//8位服务类型TOS 
    unsigned short total_len; 		//16位总长度(字节) 
    unsigned short ident; 		//16位标识 
    unsigned short frag_and_flags; 	//3位标志位 
    unsigned char ttl; 			//8位生存时间 TTL 
    unsigned char proto; 		//8位协议 (TCP, UDP 或其他) 
    unsigned short checksum; 		//16位IP首部校验和 
    unsigned int sourceIP;		//32位源IP地址 
    unsigned int destIP; 		//32位目的IP地址 
}IP_HEADER; 
typedef struct _udphdr 			//定义UDP首部
{
    unsigned short uh_sport;    	//16位源端口
    unsigned short uh_dport;    	//16位目的端口
    unsigned int uh_len;		//16位UDP包长度
    unsigned int uh_sum;		//16位校验和
}UDP_HEADER;
typedef struct _tcphdr 			//定义TCP首部 
{ 
    unsigned short th_sport; 		//16位源端口 
    unsigned short th_dport; 		//16位目的端口 
    unsigned int th_seq; 		//32位序列号 
    unsigned int th_ack; 		//32位确认号 
    unsigned char th_lenres;		//4位首部长度/6位保留字 
    unsigned char th_flag; 		//6位标志位
    unsigned short th_win; 		//16位窗口大小
    unsigned short th_sum; 		//16位校验和
    unsigned short th_urp; 		//16位紧急数据偏移量
}TCP_HEADER; 
typedef struct _icmphdr {  
    unsigned char  icmp_type;  
    unsigned char icmp_code; 
    unsigned short icmp_cksum;  
    unsigned short icmp_id;  
    unsigned short icmp_seq;    
    unsigned short icmp_timestamp;  
}ICMP_HEADER;

void analyseIP(IP_HEADER *ip);
void analyseTCP(TCP_HEADER *tcp);
void analyseUDP(UDP_HEADER *udp);
void analyseICMP(ICMP_HEADER *icmp);

#define BUFFER_MAX 2048
int main(int argc,char* argcv[]){
	int sock_fd;
	int proto;
	int n_read;
	char buffer[BUFFER_MAX];
	char *eth_head;
	char *ip_head;
	char *tcp_head;
	char *udp_head;
	char *icmp_head;
	unsigned char *p;
	if((sock_fd=socket(PF_PACKET,SOCK_RAW,htons(ETH_P_ALL)))<0){
	printf("error create raw socket \n");
	return -1; 
	}
	while(1){
	n_read = recvfrom(sock_fd,buffer,BUFFER_MAX,0,NULL,NULL);
	if(n_read < 42){
	printf("error when recv msg \n");
	}
	eth_head = buffer;
	p = eth_head;
	printf("MAC address : %.2x:%02x:%02x:%02x:%02x:%02x ==>	%.2x:%02x:%02x:%02x:%02x:%02x\n",p[6],p[7],p[8],p[9],p[10],p[11],p[0],p[1],p[2],p[3],p[4],p[5]);
	ip_head = eth_head+14;
	p = ip_head+12;
	printf("IP:%d.%d.%d.%d ==> %d.%d.%d.%d \n",p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7]);
	proto = (ip_head +9)[0];
	p = ip_head+12;
	printf("Protocol:");
	switch(proto){
	case IPPROTO_ICMP : printf("icmp\n");break;
	case IPPROTO_IGMP : printf("igmp\n");break;
	case IPPROTO_IPIP : printf("ipip\n");break;
	case IPPROTO_TCP  : printf("tcp \n");break;
	case IPPROTO_UDP  : printf("udp \n");break;
	default : printf("Pls query yourself\n");
	}
	}
	return -1;
}


你可能感兴趣的:(C/C++)