Blog‎ > ‎

Adventures in C# on Mono

posted 5 Dec 2014, 08:56 by Owen Brotherwood   [ updated 8 Dec 2014, 03:40 ]
Well, it is just Java in new clothes ...


using System;
using Ipcollector.Dialect;
using System.Net.Sockets;
using System.Net;


namespace IPcollector
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            // very basic input to get the job done
            String ipAddress = args [0];
            String port = args [1]; 
            String hostName = args [2];
            String hostState = args [3];
            String attrKey = args [4];
            String attrValue = args [5];

            Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract (new DateTime (1970, 1, 1))).TotalSeconds;

            // no error checking for now
            IPEndPoint ipEndPoint = new IPEndPoint (IPAddress.Parse (ipAddress), int.Parse (port));
            Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect (ipEndPoint);
            NetworkStream networkStream = new NetworkStream (socket, true);

            // build a very basic event
            ExternalEvent externalEvent = new ExternalEvent ();
            externalEvent.event_type = ExternalEvent.EventType.HOST;
            externalEvent.HostEvent.HostName = hostName;
            externalEvent.MessageId = unixTimestamp;
            String hostStateUpper = hostState.ToUpper();
            switch (hostStateUpper) {
            case "UP": 
                externalEvent.HostEvent.host_state = ExternalEvent.ExternalHostEvent.HostState.UP;
                break;
            case "DOWN":
                externalEvent.HostEvent.host_state = ExternalEvent.ExternalHostEvent.HostState.DOWN;
                break;
            case "UNREACHABLE":
                externalEvent.HostEvent.host_state = ExternalEvent.ExternalHostEvent.HostState.UNREACHABLE;
                break;
            }
            ExternalEvent.ExternalAttribute externalAttribute = new ExternalEvent.ExternalAttribute ();
            externalAttribute.Key = attrKey;
            externalAttribute.Value = attrValue;
            externalEvent.HostEvent.Attribute.Add (externalAttribute);

            // send event
            ExternalEvent.Serialize (networkStream, externalEvent);
        }
    }
}
Comments