- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/socket.h>
- #include <sys/ioctl.h>
- #include <netpacket/packet.h>
- #include <fcntl.h>
- #include <netinet/in.h>
- //#include <unistd.h>
- #include <net/if.h>
- #include <string.h>
- #include <linux/if_ether.h>
- /* 4 bytes IP address */
- typedef struct ip_address{
- u_char byte1;
- u_char byte2;
- u_char byte3;
- u_char byte4;
- }ip_address;
- /* IPv4 header */
- typedef struct ip_header{
- u_char ver_ihl; // Version (4 bits) + Internet header length (4 bits)
- u_char tos; // Type of service
- u_short tlen; // Total length
- u_short identification; // Identification
- u_short flags_fo; // Flags (3 bits) + Fragment offset (13 bits)
- u_char ttl; // Time to live
- u_char proto; // Protocol
- u_short crc; // Header checksum
- ip_address saddr; // Source address
- ip_address daddr; // Destination address
- // u_int op_pad; // Option + Padding
- }ip_header;
- /* UDP header*/
- typedef struct udp_header{
- u_short sport; // Source port
- u_short dport; // Destination port
- u_short len; // Datagram length
- u_short crc; // Checksum
- }udp_header;
- //typedef struct eth_header{
- //
- //}
- int getifindex(int fd,char *ifname)
- {
- struct ifreq ifr;
- memset(&ifr,0,sizeof(ifr));
- strcpy(ifr.ifr_name,ifname);
- if(-1 == ioctl(fd,SIOCGIFINDEX,&ifr))
- {
- printf("ioctl error\\n");
- return -1;
- }
- return ifr.ifr_ifindex;
- }
- int main()
- {
- int fd;
- int n;
- int i;
- unsigned char buf[1500];
- struct sockaddr_ll sll;
- fd = socket(PF_PACKET,SOCK_RAW,htons(ETH_P_IP));
- if(-1 == fd)
- {
- printf("Create socket error!\\n");
- return -1;
- }
- sll.sll_family = PF_PACKET;
- sll.sll_ifindex = getifindex(fd,"eth0");
- sll.sll_protocol = htons(ETH_P_IP);
- if(-1 == bind(fd,(struct sockaddr *)&sll,sizeof(sll)))
- {
- printf("Bind error!\\n");
- return -1;
- }
- while(1)
- {
- n = recv(fd,buf,1500,0);
- printf("\\n-------------\\nrecv %d bytes \\n",n);
- // for(i=1;i<=n;i++)
- // {
- // printf("%02x ",buf[i]);
- // if((0!=i)&&(i%16==0))
- // {
- // printf("\\n");
- // }
- // }
- ip_header *ipheader;
- ipheader = (struct ip_header *)&buf[14];
- printf("sourceIP:%d.%d.%d.%d\\n",ipheader->saddr.byte1,ipheader->saddr.byte2,ipheader->saddr.byte3,ipheader->saddr.byte4);
- printf("destinationIP:%d.%d.%d.%d\\n",ipheader->daddr.byte1,ipheader->daddr.byte2,ipheader->daddr.byte3,ipheader->daddr.byte4);
- if(6 == (int)ipheader->proto)
- {
- printf("TCP Packet\\n");
- }
- else if(17 == (int)ipheader->proto)
- {
- printf("UDP Packet\\n");
- }
- }
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/1010201513774.html
来源: http://www.codesnippet.cn/detail/1010201513774.html