Using the FEZ Panda II with Ethernet Connect shield and cable connecting the Connect shield to my PC, I’m trying to do two things: A) make Debug.Print show the assigned IP address, and B) ping a network device, such as the PC.
Attempting to do the ping test first, tried the following (borrowed from andre.marschalek), but get an unexplained system error on line “Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);”. Maybe, there’s a better way to do a simple ping test? Here’s my code:
using System;
using System.Net;
using System.Net.Sockets;
using Microsoft.SPOT;
using Socket = System.Net.Sockets.Socket;
namespace MFConsoleApplication8
{
public class Program
{
public static void Main()
{
if (Ping("192.168.0.1"))
Debug.Print("success");
else
Debug.Print("failed");
}
private static byte lastSequenceNr = 0;
private static byte[] pingCommand;
public static bool Ping(string address)
{
bool result = false;
byte[] receiveBuffer = new byte[540];
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 0);
IPEndPoint responseEndPoint = new IPEndPoint(IPAddress.Any, 0);
EndPoint castResponseEndPoint = (EndPoint)responseEndPoint;
pingCommand = new byte[8];
pingCommand[0] = 8; // Type
pingCommand[1] = 0; // Subtype
pingCommand[2] = 0; // Checksum
pingCommand[3] = 0;
pingCommand[4] = 1; // Identifier
pingCommand[5] = 0;
pingCommand[6] = 0; // Sequence number
pingCommand[7] = 0;
Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
mySocket.Bind(localEndPoint);
mySocket.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.IpTimeToLive,
128
);
mySocket.ReceiveTimeout = 10;
DateTime timeSend = DateTime.Now;
Debug.Print(timeSend.ToString());
pingCommand[6] = lastSequenceNr++;
SetChecksum(pingCommand);
mySocket.SendTo(pingCommand, pingCommand.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(address), 0));
Debug.Print("sended");
try
{
int Brecieved = mySocket.ReceiveFrom(
receiveBuffer,
0,
receiveBuffer.Length,
SocketFlags.None,
ref castResponseEndPoint
);
if ((receiveBuffer[20] == 0) && (pingCommand[4] == receiveBuffer[24]) && (pingCommand[5] == receiveBuffer[25]) &&
(pingCommand[6] == receiveBuffer[26]) && (pingCommand[7] == receiveBuffer[27]))
{
Debug.Print("response received");
Debug.Print(DateTime.Now.Subtract(timeSend).ToString());
result = true;
}
}
catch (SocketException e)
{
if (e.ErrorCode != (int)SocketError.TimedOut)
{
Debug.Print("unexpected error: " + e.ErrorCode);
}
}
mySocket.Close();
return result;
}
private static void SetChecksum(byte[] tel)
{
tel[2] = 0;
tel[3] = 0;
uint cs = 0;
for (int i = 0; i < pingCommand.Length; i = i + 2)
cs += (UInt16)(pingCommand[0 + i] << 0 | pingCommand[1 + i] << 8);
cs = ~((cs & 0xffffu) + (cs >> 16));
tel[2] = (byte)cs;
tel[3] = (byte)(cs >> 8);
}
public static UInt16 ToUInt16(byte[] value, int index = 0) { return (UInt16)(value[0 + index] << 0 | value[1 + index] << 8); }
}
}