Компьютерные сети
- 3 ответа
- 0 вопросов
2
Вклад в тег
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
namespace icmp_client
{
public class IcmpClient
{
// args[0] can be an IPaddress or host name.
// args[1] message for send
public static void Main (string[] args)
{
Ping pingSender = new Ping ();
PingOptions options = new PingOptions ();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = args[1];
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
PingReply reply = pingSender.Send(args[0], timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Address: {0}", reply.Address.ToString ());
Console.WriteLine("Message: {0}", data);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
}
}
}
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace icmp_server
{
public class IcmpServer
{
private const int ICMP_TYPE_OFFSET = 20;
private const int ICMP_TYPE_ECHO_REQUEST = 8;
private const int PAYLOAD_OFFSET = 28;
public static void Main(string[] args)
{
IPAddress ipAddr = IPAddress.Parse(args[0]);
IPEndPoint ipMyEndPoint = new IPEndPoint(ipAddr, 0);
EndPoint myEndPoint = (ipMyEndPoint);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
socket.Bind(myEndPoint);
socket.IOControl(IOControlCode.ReceiveAll, BitConverter.GetBytes(1), null);
while (true)
{
Byte[] ReceiveBuffer = new Byte[socket.ReceiveBufferSize];
var nBytes = socket.ReceiveFrom(ReceiveBuffer, ReceiveBuffer.Length, SocketFlags.None, ref myEndPoint);
var icmpType = ReceiveBuffer[ICMP_TYPE_OFFSET];
if (icmpType == ICMP_TYPE_ECHO_REQUEST)
{
Console.WriteLine("Echo Request received");
Console.WriteLine("Received: {0} bytes", nBytes);
if(nBytes > PAYLOAD_OFFSET)
{
var payLoadSize = nBytes - PAYLOAD_OFFSET;
byte[] payLoad = new byte[payLoadSize];
Array.Copy(ReceiveBuffer, PAYLOAD_OFFSET, payLoad, 0, payLoadSize);
string msg = Encoding.ASCII.GetString(payLoad);
Console.WriteLine("Data hex: {0}", BitConverter.ToString(payLoad));
Console.WriteLine("Data text: {0}", msg);
}
Console.WriteLine("---------------");
}
}
}
}
}
Правильно заданный вопрос - это уже половина ответа