/*---------------------------------------------------------------------------*
  Project:  socket test
  File:     ping.c

  Copyright 2006 Nintendo.  All rights reserved.

  These coded instructions, statements, and computer programs contain
  proprietary information of Nintendo of America Inc. and/or Nintendo
  Company Ltd., and are protected by Federal copyright law.  They may
  not be disclosed to third parties or copied or duplicated in any form,
  in whole or in part, without the prior written consent of Nintendo.

 *---------------------------------------------------------------------------*/

#include <ios.h>
#include <iostypes.h>
#include <ioslibc.h>
#include <socket.h>

#define STACK_SIZE          (4 * 1024)
const u8 _initStack[STACK_SIZE] __attribute__ ((aligned (4)));
const u32 _initStackSize = sizeof(_initStack);
const u32 _initPriority = 10;

#define IPC_ATTR        __attribute__((aligned(32)))
#define OSReport        printf

#define OS_BUS_CLOCK                    162000000u
#define OS_TIMER_CLOCK                  (OS_BUS_CLOCK/4)
#define OSSecondsToTicks(x)             ((((x) * (OS_TIMER_CLOCK/125000)) / 8) * 1000000)

// Destination IP address
const u8 Destination[4]      = {  10,   0,   0, 177 };

SOConfig Config IPC_ATTR =
{
    SO_VENDOR_NINTENDO,
    SO_VERSION,

    0,
    0,

    SO_FLAG_DHCP,

    { SO_INADDR_ANY },
    { SO_INADDR_ANY },
    { SO_INADDR_ANY },
    { SO_INADDR_ANY },
    { SO_INADDR_ANY },

    4096,
    4096
};

char     data[33] IPC_ATTR = "01234567890123456789012345678901";

int main(void)
{
    SOSockAddrIn remote IPC_ATTR;
    s32          result;
    int          i;
    int          fd;

    SOiStartup(&Config); // DHCP
    while ((u32) SOGetHostID() == SOHtoNl(SO_INADDR_ANY))
    {
        ;
    }

    memcpy(&remote.addr.addr, Destination, IP_ALEN);
    remote.len    = sizeof(SOSockAddrIn);
    remote.family = SO_PF_INET;
    remote.port   = 0;

    fd = ICMPSocket(SO_PF_INET);
    for (i = 0; i < 4; ++i)
    {
        result = ICMPPing(fd, data, sizeof data, &remote, OSSecondsToTicks(3));

        switch (result)
        {
          case 0:
            OSReport("Reply.\n");
            break;
          case SO_ETIMEDOUT:
            OSReport("Request timed out.\n");
            break;
          default:
            OSReport("Error %d.\n", result);
            break;
        }
    }

    ICMPClose(fd);

    SOiCleanup();

    OSReport("Done.\n");
    return 0;
}
