/*
 * raw.c
 *
 *  Created on: 2015-6-2
 *      Author: hjj
 */
#include <netmain.h>
#include <cslr_emac.h>

#define ETH_P_IP 0x0800
#define EMAC_REGS                 ((CSL_EmacRegs *)0x02C80000u)

void raw()
{
	IPN IPAddr;
	SOCKET sock = INVALID_SOCKET;
	int flag = 1;
	struct   sockaddr_in sin1;
    struct   timeval timeout;
	Uint8 masterChannel=0;
    HANDLE   hBuffer;
    char     *pBuf;
    char	 RecvBuf[65535];
    // Allocate the file environment for this task
    fdOpenSession( TaskSelf() );

    // Create the raw socket
//    sock = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
    sock = socket(AF_INET, SOCK_RAW, htons(ETH_P_IP));
    if(sock == INVALID_SOCKET)
    {
    	printf("socket create failed!\n");
    }

    //设置IP头操作选项，其中flag设置为true，亲自对IP头进行处理
    if(0 != setsockopt(sock,IPPROTO_IP,IP_HDRINCL,(char*)&flag,sizeof(flag)))
    {
    	printf("setsockopt failed!\n");
    }
/*
    IPAddr=inet_addr("192.168.1.18");
    // Set Port = 217, leaving IP address = Any
    bzero( &sin1, sizeof(struct sockaddr_in) );
    sin1.sin_family = AF_INET;
    sin1.sin_addr.s_addr = IPAddr;
    sin1.sin_port   = htons(457);

    // Bind socket
    if (0 != bind(sock,(PSA) &sin1,sizeof(sin1)))
    {
    	printf("bind failed!\n");
    }
*/
    timeout.tv_sec  = 15;
    timeout.tv_usec = 0;
    setsockopt( sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof( timeout ) );
    setsockopt( sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof( timeout ) );

    //设置网卡为混杂模式
    EMAC_REGS->MACADDRLO = 0x80000;
    CSL_FINST(EMAC_REGS->RXMBPENABLE, EMAC_RXMBPENABLE_RXPASSCRC, INCLUDE);
    CSL_FINST(EMAC_REGS->RXMBPENABLE, EMAC_RXMBPENABLE_RXQOSEN, ENABLE);
    CSL_FINST(EMAC_REGS->RXMBPENABLE, EMAC_RXMBPENABLE_RXNOCHAIN, ENABLE);
    CSL_FINST(EMAC_REGS->RXMBPENABLE, EMAC_RXMBPENABLE_RXCMFEN, ENABLE);
    CSL_FINST(EMAC_REGS->RXMBPENABLE, EMAC_RXMBPENABLE_RXCSFEN, ENABLE);
    CSL_FINST(EMAC_REGS->RXMBPENABLE, EMAC_RXMBPENABLE_RXCEFEN, ENABLE);
    CSL_FINST(EMAC_REGS->RXMBPENABLE, EMAC_RXMBPENABLE_RXCAFEN, ENABLE);
	CSL_FINS(EMAC_REGS->RXMBPENABLE, EMAC_RXMBPENABLE_RXPROMCH, masterChannel);

    for(;;)
    {

    	int    ret;
//    	int    cnt;
    	ret = recv(sock,RecvBuf,65535,0);
//    	cnt = (int)recvnc( sock, (void **)&pBuf, 0, &hBuffer );
		printf("ing\n");
		if( ret > 0 )
		{
			printf("%s",RecvBuf);

		}
		/*
		if( cnt > 0 )
		{
			printf("%s",*pBuf);

		}*/
		else
		{
			printf("the connection has been closed.\n");
		}
    }
}



