echotcp.c

来自「dsp 的内核编程在此呢」· C语言 代码 · 共 119 行

C
119
字号
#include <csl.h>
#include <csl_chip.h>
#include <csl_chiphal.h>
#include <csl_emac.h>
#include <csl_emachal.h>
#include <csl_emifa.h>
#include <csl_emifahal.h>
#include <csl_gpio.h>
#include <csl_gpiohal.h>
#include <csl_i2c.h>
#include <csl_i2chal.h>
#include <csl_irq.h>
#include <csl_irqhal.h>
#include <csl_mdio.h>
#include <csl_stdinc.h>
#include <csl_stdinchal.h>
#include <csl_timer.h>
#include <csl_timerhal.h>
#include <seeddm642.h>
#include <std.h>
 


void EchoTcp( IPN IPAddr )
{
  SOCKET s;
  struct sockaddr_in sin1;
  int i;
  char *pBuf = 0;
  struct timeval timeout;
   
   // Allocate the file descriptor envir
  fdOpenSession( (HANDLE)TSK_self() );
  
  /*--onment for this task--*/
  printf("\n== Start TCP Echo Client Test ==\n");
  
  // Create test socket
  s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if( s < 0 )
  {
   printf("failed socket create (%d)\n",fdError());
   goto leave;
  }
  
  // Prepare address for connect
  bzero( &sin1, sizeof(struct sockaddr_in) );
  sin1.sin_family = AF_INET;
  sin1.sin_len = sizeof( sin1 );
  sin1.sin_addr.s_addr = IPAddr;
  sin1.sin_port = htons(7);
  
  // Configure our Tx and Rx timeout to be 5 seconds
  timeout.tv_sec = 5;
  timeout.tv_usec = 0;
  setsockopt( s, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof( timeout ) );
  setsockopt( s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof( timeout ) );

  // Connect socket
  if( connect( s, (PSA) &sin1, sizeof(sin1) ) < 0 )
  {
    printf("failed connect (%d)\n",fdError());
    goto leave;
  }

  // Allocate a working buffer
  if( !(pBuf = malloc( 4096 )) )
  {
    printf("failed temp buffer allocation\n");
    goto leave;
  }

  // Fill buffer with a test pattern
  for(i=0; i<4096; i++)
    *(pBuf+i) = (char)i;
   
   /*---28 TCP/IP NDK User's Guide---*/
   // Send the buffer
   if( send( s, pBuf, 4096, 0 ) < 0 )
   {
      printf("send failed (%d)\n",fdError());
      goto leave;
   }

    // Try and receive the test pattern back
   i = recv( s, pBuf, 4096, MSG_WAITALL );
   if( i < 0 )
   {
      printf("recv failed (%d)\n",fdError());
      goto leave;
   }

   // Verify reception size and pattern
   if( i != test )
   {
     printf("received %d (not %d) bytes\n",i,test);
     goto leave;
   }
   
   for(i=0; i<test; i++)
   if( *(pBuf+i) != (char)i )
   {
      printf("verify failed at byte %d\n",i);
      break;
   }
   
  // If here, the test passed
  if( i==test )
  printf("passed\n");
leave:
  if( pBuf )
  free( pBuf );
  if( s >= 0 )
  fdClose( s );
  printf("== End TCP Echo Client Test ==\n\n");
  // Free the file descriptor environment for this task
  fdCloseSession( (HANDLE)TSK_self() );
  TSK_exit();
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?