/* C# Network Programming by Richard Blum Publisher: Sybex ISBN: 0782141765 */ using System.Net; using System.Net.Sockets; using System.Text; using System; public class MacAddress { public static void Main(string[] argv) { int commlength, miblength, datastart, datalength; string nextmib, value; SNMP conn = new SNMP(); string mib = "1.3.6.1.2.1.17.4.3.1.1"; int orgmiblength = mib.Length; byte[] response = new byte[1024]; nextmib = mib; while (true) { response = conn.get("getnext", argv[0], argv[1], nextmib); commlength = Convert.ToInt16(response[6]); miblength = Convert.ToInt16(response[23 + commlength]); datalength = Convert.ToInt16(response[25 + commlength + miblength]); datastart = 26 + commlength + miblength; value = BitConverter.ToString(response, datastart, datalength); nextmib = conn.getnextMIB(response); if (!(nextmib.Substring(0, orgmiblength) == mib)) break; Console.WriteLine("{0} = {1}", nextmib, value); } } } class SNMP { public SNMP() { } public byte[] get(string request, string host, string community, string mibstring) { byte[] packet = new byte[1024]; byte[] mib = new byte[1024]; int snmplen; int comlen = community.Length; string[] mibvals = mibstring.Split('.'); int miblen = mibvals.Length; int cnt = 0, temp, i; int orgmiblen = miblen; int pos = 0; // Convert the string MIB into a byte array of integer values // Unfortunately, values over 128 require multiple bytes // which also increases the MIB length for (i = 0; i < orgmiblen; i++) { temp = Convert.ToInt16(mibvals[i]); if (temp > 127) { mib[cnt] = Convert.ToByte(128 + (temp / 128)); mib[cnt + 1] = Convert.ToByte(temp - ((temp / 128) * 128)); cnt += 2; miblen++; } else { mib[cnt] = Convert.ToByte(temp); cnt++; } } snmplen = 29 + comlen + miblen - 1; //Length of entire SNMP packet //The SNMP sequence start packet[pos++] = 0x30; //Sequence start packet[pos++] = Convert.ToByte(snmplen - 2); //sequence size //SNMP version packet[pos++] = 0x02; //Integer type packet[pos++] = 0x01; //length packet[pos++] = 0x00; //SNMP version 1 //Community name packet[pos++] = 0x04; // String type packet[pos++] = Convert.ToByte(comlen); //length //Convert community name to byte array byte[] data = Encoding.ASCII.GetBytes(community); for (i = 0; i < data.Length; i++) { packet[pos++] = data[i]; } //Add GetRequest or GetNextRequest value if (request == "get") packet[pos++] = 0xA0; else packet[pos++] = 0xA1; packet[pos++] = Convert.ToByte(20 + miblen - 1); //Size of total MIB //Request ID packet[pos++] = 0x02; //Integer type packet[pos++] = 0x04; //length packet[pos++] = 0x00; //SNMP request ID packet[pos++] = 0x00; packet[pos++] = 0x00; packet[pos++] = 0x01; //Error status packet[pos++] = 0x02; //Integer type packet[pos++] = 0x01; //length packet[pos++] = 0x00; //SNMP error status //Error index packet[pos++] = 0x02; //Integer type packet[pos++] = 0x01; //length packet[pos++] = 0x00; //SNMP error index //Start of variable bindings packet[pos++] = 0x30; //Start of variable bindings sequence packet[pos++] = Convert.ToByte(6 + miblen - 1); // Size of variable binding packet[pos++] = 0x30; //Start of first variable bindings sequence packet[pos++] = Convert.ToByte(6 + miblen - 1 - 2); // size packet[pos++] = 0x06; //Object type packet[pos++] = Convert.ToByte(miblen - 1); //length //Start of MIB packet[pos++] = 0x2b; //Place MIB array in packet for(i = 2; i < miblen; i++) packet[pos++] = Convert.ToByte(mib[i]); packet[pos++] = 0x05; //Null object value packet[pos++] = 0x00; //Null //Send packet to destination Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000); IPHostEntry ihe = Dns.Resolve(host); IPEndPoint iep = new IPEndPoint(ihe.AddressList[0], 161); EndPoint ep = (EndPoint)iep; sock.SendTo(packet, snmplen, SocketFlags.None, iep); //Receive response from packet try { int recv = sock.ReceiveFrom(packet, ref ep); } catch (SocketException) { packet[0] = 0xff; } return packet; } public string getnextMIB(byte[] mibin) { string output = "1.3"; int commlength = mibin[6]; int mibstart = 6 + commlength + 17; //find the start of the mib section //The MIB length is the length defined in the SNMP packet // minus 1 to remove the ending .0, which is not used int miblength = mibin[mibstart] - 1; mibstart += 2; //skip over the length and 0x2b values int mibvalue; for(int i = mibstart; i < mibstart + miblength; i++) { mibvalue = Convert.ToInt16(mibin[i]); if (mibvalue > 128) { mibvalue = (mibvalue/128)*128 + Convert.ToInt16(mibin[i+1]); i++; } output += "." + mibvalue; } return output; } }
JSON (JavaScript Object Notation) Utility Methods.
using System.Collections.Generic; using System.Text; namespace Facebook.Utility { /// <summary> /// JSON (JavaScript Object Notation) Utility Methods. /// </summary> public static class JSONHelper { ///<summary> /// Converts a Dictionary to a JSON-formatted Associative Array. ///</summary> ///<param name="dict">Source Dictionary collection [string|string].</param> ///<returns>JSON Associative Array string.</returns> public static string ConvertToJSONAssociativeArray(Dictionary<string, string> dict) { var elements = new List<string>(); foreach (var pair in dict) { if(!string.IsNullOrEmpty(pair.Value)) { elements.Add(string.Format(""{0}":{2}{1}{2}", EscapeJSONString(pair.Key), EscapeJSONString(pair.Value), IsJSONArray(pair.Value) || IsBoolean(pair.Value) ? string.Empty : """)); } } return "{" + string.Join(",", elements.ToArray()) + "}"; } /// <summary> /// Determines if input string is a formatted JSON Array. /// </summary> /// <param name="test">string</param> /// <returns>bool</returns> public static bool IsJSONArray(string test) { return test.StartsWith("{") && !test.StartsWith("{*") || test.StartsWith("["); } /// <summary> /// Determines if input string is a boolean value. /// </summary> /// <param name="test">string</param> /// <returns>bool</returns> public static bool IsBoolean(string test) { return test.Equals("false") || test.Equals("true"); } /// <summary> /// Converts a List collection of type string to a JSON Array. /// </summary> /// <param name="list">List of strings</param> /// <returns>string</returns> public static string ConvertToJSONArray(List<string> list) { if (list == null || list.Count == 0) { return "[]"; } StringBuilder builder = new StringBuilder(); builder.Append("["); foreach (var item in list) { builder.Append(string.Format("{0}{1}{0},", IsJSONArray(item) || IsBoolean(item) ? string.Empty : """, EscapeJSONString(item))); } builder.Replace(",", "]", builder.Length - 1, 1); return builder.ToString(); } /// <summary> /// Converts a List collection of type long to a JSON Array. /// </summary> /// <param name="list">List of longs</param> /// <returns>string</returns> public static string ConvertToJSONArray(List<long> list) { if (list == null || list.Count == 0) { return "[]"; } StringBuilder builder = new StringBuilder(); builder.Append("["); foreach (var item in list) { builder.Append(string.Format("{0}{1}{0},", IsJSONArray(item.ToString()) || IsBoolean(item.ToString()) ? string.Empty : """, EscapeJSONString(item.ToString()))); } builder.Replace(",", "]", builder.Length - 1, 1); return builder.ToString(); } /// <summary> /// Converts a JSON Array string to a List collection of type string. /// </summary> /// <param name="array">JSON Array string</param> /// <returns>List of strings</returns> public static List<string> ConvertFromJSONArray(string array) { if (!string.IsNullOrEmpty(array)) { array = array.Replace("[", "").Replace("]", "").Replace(""", ""); return new List<string>(array.Split(',')); } return new List<string>(); } /// <summary> /// Converts a JSON Array string to a Dictionary collection of type string, string. /// </summary> /// <param name="array">JSON Array string</param> /// <returns>Dictionary of string, string</returns> public static Dictionary<string, string> ConvertFromJSONAssoicativeArray(string array) { var dict = new Dictionary<string, string>(); if (!string.IsNullOrEmpty(array)) { array = array.Replace("{", "").Replace("}", "").Replace("":", "|").Replace(""", "").Replace("/", "/"); var pairs = new List<string>(array.Split(',')); foreach (var pair in pairs) { if (!string.IsNullOrEmpty(pair)) { var pairArray = pair.Split('|'); dict.Add(pairArray[0], pairArray[1]); } } return dict; } return new Dictionary<string, string>(); } /// <summary> /// Escape backslashes and double quotes of valid JSON content string. /// </summary> /// <param name="originalString">string</param> /// <returns>string</returns> public static string EscapeJSONString(string originalString) { return IsJSONArray(originalString) ? originalString : originalString.Replace("/", "/").Replace("/", "/").Replace(""", """).Replace(""", """).Replace(" ", " ").Replace(" ", " "); } } }
IPHostEntry.HostName
using System; using System.Collections.Generic; using System.Text; using System.Net; //DnsLookup class Program { static void Main(string[] args) { IPHostEntry ipHostEntry = Dns.GetHostEntry("www.google.com"); Console.WriteLine("Host: {0}", ipHostEntry.HostName); if (ipHostEntry.Aliases.Length > 0) { Console.WriteLine(" Aliases:"); foreach (string alias in ipHostEntry.Aliases) { Console.WriteLine(alias); } } Console.WriteLine(" Address(es):"); foreach (IPAddress address in ipHostEntry.AddressList) { Console.WriteLine("Address: {0}", address.ToString()); } } }
IPAddress: AddressFamily,MinPort,MaxPort,Serialize
using System; using System.Net; class IPEndPointSample { public static void Main() { IPAddress test1 = IPAddress.Parse("192.168.1.1"); IPEndPoint ie = new IPEndPoint(test1, 8000); Console.WriteLine("The IPEndPoint is: {0}",ie.ToString()); Console.WriteLine("The AddressFamily is: {0}",ie.AddressFamily); Console.WriteLine("The address is: {0}, and the port is: {1} ", ie.Address, ie.Port); Console.WriteLine("The min port number is: {0}",IPEndPoint.MinPort); Console.WriteLine("The max port number is: {0} ",IPEndPoint.MaxPort); ie.Port = 80; Console.WriteLine("The changed IPEndPoint value is: {0}", ie.ToString()); SocketAddress sa = ie.Serialize(); Console.WriteLine("The SocketAddress is: {0}",sa.ToString()); } }
new IPEndPoint(IPAddress.Parse(“127.0.0.1”), 8888)
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; class MainClass { private static void Main() { IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888); Thread receiveThread = new Thread(ReceiveData); receiveThread.IsBackground = true; receiveThread.Start(); UdpClient client = new UdpClient(); try { string text = "message"; byte[] data = Encoding.UTF8.GetBytes(text); client.Send(data, data.Length, remoteEndPoint); } catch (Exception err) { Console.WriteLine(err.ToString()); } finally { client.Close(); } } private static void ReceiveData() { UdpClient client = new UdpClient(5555); while (true) { try { IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0); byte[] data = client.Receive(ref anyIP); string text = Encoding.UTF8.GetString(data); Console.WriteLine(">> " + text); } catch (Exception err) { Console.WriteLine(err.ToString()); } } } }
Get Host IP Address
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // * Neither the name of Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Text; using System.Net; namespace WOSI.Utilities { public class NetworkUtils { public static IPAddress GetHostIPAddress(string hostName, System.Net.Sockets.AddressFamily addressFamily) { try { // If there's a port, remove it if (hostName.Contains(":")) hostName = hostName.Split(':')[0]; IPAddress parsedAddress; if (IPAddress.TryParse(hostName, out parsedAddress)) return parsedAddress; IPHostEntry ipEntry = Dns.GetHostEntry(hostName); if (ipEntry.AddressList.Length > 0) { foreach (IPAddress address in ipEntry.AddressList) { if (address.AddressFamily == addressFamily && address.GetAddressBytes()[0] > 0) return address; } } } catch { } return new IPAddress(0); } } }
Get Current Ip Address
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // * Neither the name of Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Text; using System.Net; namespace WOSI.Utilities { public class NetworkUtils { public static string GetCurrentIpAddress() { string hostname = Dns.GetHostName(); IPAddress[] ips = Dns.GetHostAddresses(hostname); string ip = String.Empty; if (ips.Length > 0) { ip = ips[0].ToString(); } return ip; } } }