C#: Internet & Networking

person Jason Huangfolder_openC#, Codelocal_offer, , , , , , access_time October 6, 2009

The following short pieces of code show you how to:
– Ping an IP address
– Send an email in .NET with authenticated user (not anonymous email host)
– How to do a simple HTTP request using .NET

Ping IP

//requires .NET framework 2.0
        public static string PingIP(string commandStr)
        {
            string output = "";
 
            System.Net.NetworkInformation.Ping myPing = new System.Net.NetworkInformation.Ping();
            System.Net.NetworkInformation.PingReply myReply = myPing.Send(commandStr);
 
            output = "Ping [" + commandStr + "] returns status " +  myReply.Status.ToString() + ": ";
 
            if (myReply.Status == System.Net.NetworkInformation.IPStatus.Success)
            {
                output += "Address: " + myReply.Address.ToString() + "\t";
                output += "RTT: " + myReply.RoundtripTime.ToString() + "\t";
                output += "TTL: " + myReply.Options.Ttl.ToString() + "\t";
            }
 
            return output;
        }

Send Email using Authenticated SMTP Server

/*The following code uses .NET 2.0 framework, and it could use SMTP server that requires SSL & user/password authentifcation, such as the gmail server.
 
Point to remember: when using secured SMTP server, need to set UseDefaultCredential to false, otherwise it will not use the new NetworkCredential you set; Also have to make .EnableSsl = true if the server requires it.
*/
 
using System.Net.Mail;
        private void test()
        {
            System.Collections.Hashtable ht = new System.Collections.Hashtable();
            ht["To"] = "to_somebody@mail.com";
            ht["From"] = "from_somebody@mail.com";
            ht["Subject"] = "Subject of the email here";
            ht["Body"] = "body of test email message.";
            ht["smtp"] = "smtp.mail.com";  //whatever your smtp server host name is
            ht["User"] = "user_mail@mail.com"; //what your user name is for login to secured SMTP mail server
            ht["Password"] = "somepassword"; //password for login to SMTP mail server.
 
            util.SendEmail(ht);
        }
        //this is a helper function that actually sends the email
        public static void SendEmail(System.Collections.Hashtable ht)
        {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(ht["From"].ToString());
            msg.To.Add(ht["To"].ToString());
            msg.Subject = ht["Subject"].ToString();
            msg.Body = ht["Body"].ToString();
            //msg.Bcc.Add(ht["BCC"].ToString());
            msg.Priority = MailPriority.Normal;
 
            //That is where the SMTP server authentication takes place
            SmtpClient smp = new SmtpClient(ht["smtp"].ToString());
            smp.UseDefaultCredentials = false;
            //use SSL to login
            smp.EnableSsl = true;
            //pass the user name and password to credential
            System.Net.NetworkCredential smtpCredential =
				new System.Net.NetworkCredential(ht["User"].ToString(), ht["Password"].ToString());
            smp.Credentials = smtpCredential;
            smp.Send(msg);
        }

Simple HTTP Request

//This example code simply takes www.microsoft.com and print out its http response and header info
 
using System.Net;
using System.IO;
 
        static void Main(string[] args)
        {
            string URL = "http://www.microsoft.com";
            try
            {
                //System.Net.WebProxy wp = new WebProxy("http://mcd-server/mcd/proxy.pac");
 
                Uri uriObj = new Uri(URL);
                HttpWebRequest request = (System.Net.HttpWebRequest) WebRequest.CreateDefault(uriObj);
                //request.Proxy = wp;
 
                System.Net.WebResponse myResp = request.GetResponse();
 
                Stream s = myResp.GetResponseStream();
                StreamReader reader = new StreamReader(s, System.Text.Encoding.ASCII);
                String respHTML = reader.ReadToEnd();
                Console.WriteLine(respHTML);
 
                for (int i = 0; i < myResp.Headers.Count; i++)
                {
                    Console.WriteLine(myResp.Headers[i].ToString());
                }
            }
            catch(WebException exp)
            {
                Console.WriteLine(exp.Message);
            }

Comments

  1. However I observed that when the object started to move, it
    sounded like the sound barrier was dexter missouri bearcats broken.
    Half a freaking ounce. I have cafe curtains in my bedroom and I was done.
    When even a movie’s premise seems awful, the movie itself probably isn’t much
    better, but slowly I wasn’t looking forward to wearing her wedding ring again. Mash up season continues this Saturday, December 15, as dexter missouri bearcats’s Cowboy Capital Rollergirls.
    Side note: I had a red bull and peanut butter.

  2. This post will help the internet viewers for building
    up new weblog or even a blog from start to end.

  3. Many thanks for other sorts of helpful website. The place altogether different could I am getting that kind of info coded in this kind of excellent approach? I own a task that we are only at this moment running upon, and I’ve been on the appearance out there to get similarly info.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>