Network Programming - Ping_Email_Web.pptx
Document Details

Uploaded by CongenialRooster5703
Al-Razi University
Full Transcript
Ping Ping Class Allow an application to determine whether a remote computer is accessible over the network. Methods: Send: you can pass the following parameters Name or ip address Data to be included in the ICMP packet payload Packet options (TTL and Don’t...
Ping Ping Class Allow an application to determine whether a remote computer is accessible over the network. Methods: Send: you can pass the following parameters Name or ip address Data to be included in the ICMP packet payload Packet options (TTL and Don’t Fragment flags) using PingOptions class Return PingReply object PingReply Class Properties: Status (of type IPStatus) Buffer: gets the received buffer inside the ICMP echo reply message. Options (of type PingOptions) Address: of the sender RoundtripTime: in milliseconds Assignment Create a tool like tracert using Ping class to trace the connection to the destination Scan Alive PCs on Local Broadcast Domain What will you do if firewall is configured to prevent echo reply from being sent? Use arp –a command line with Process class Process process = new Process { StartInfo = new ProcessStartInfo { FileName = "cmd.exe", // Run cmd Arguments = "/c arp -a", // Command to execute RedirectStandardOutput = true, // Capture standard output RedirectStandardError = true, // Capture error output UseShellExecute = false, // Required for redirection CreateNoWindow = true // Do not show command window } }; process.Start(); string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); process.WaitForExit(); Email Classes SmtpClient MailMessage MailAddress Attachment SmtpClient SmtpClient client = new SmtpClient(); client.Host = "mail.myserver.com"; client.Send("[email protected]", "[email protected]", "subject", "body"); Mail MailMessage MailAddress MailAddressCollection: Attachment Configure Connection // SMTP server details string smtpServer = "smtp.gmail.com"; int smtpPort = 587; string smtpUsername = "[email protected]"; string smtpPassword = "your-email-password"; // Create an SMTP client SmtpClient smtpClient = new SmtpClient(smtpServer) { Port = smtpPort, Credentials = new NetworkCredential(smtpUsername, smtpPassword), EnableSsl = true, }; Create a Mail Message Can be normal text or rich text (html) SmtpClient client = new SmtpClient(); client.Host = "mail.myisp.net"; MailMessage mm = new MailMessage(); mm.Sender = new MailAddress("[email protected]", "Kay"); mm.From = new MailAddress("[email protected]", "Kay"); mm.To.Add(new MailAddress("[email protected]", "Bob")); mm.CC.Add(new MailAddress("[email protected]", "Dan")); mm.Subject = "Hello!"; mm.Body = "Hi there. Here's the photo!"; mm.IsBodyHtml = false; mm.Priority = MailPriority.High; Attachment a = new Attachment("photo.jpg", System.Net.Mime.MediaTypeNames.Image.Jpeg); mm.Attachments.Add(a); client.Send(mm); How to Receive a Message POP3 IMAP DHCP Server DHCP Server Protocol Assignment Explain DHCP protocol and list all RFCs related to Explain bootp Web Client Web Addresses A URI is a specially formatted string that describes a resource on the internet or a LAN, such as a web page, file, or email address. Examples: http://www.ietf.org, ftp://myisp/doc.txt, and mailto:[email protected]. URI URI | Uri Class The Uri class is useful when you need to validate the format of a URI string or to split a URI into its component parts. Otherwise, you can treat a URI simply as a string You can construct a Uri object by passing any of the following strings into its constructor: A URI string, such as http://www.ebay.com or file://janespc/sharedpics/dolphin.jpg An absolute path to a file on your hard disk, such as c:\myfiles\ data.xlsx or, on Unix, /tmp/myfiles/data.xlsx A UNC path to a file on the LAN, such as \\janespc\sharedpics\ dolphin.jpg Uri Uri objects have read-only properties. To modify an existing Uri, instantiate a UriBuilder object, which has writable properties and can be converted back via its Uri property. Uri info = new Uri("http://www.domain.com:80/info/"); Uri page = new Uri("http://www.domain.com/info/page.html"); Console.WriteLine(info.Host); // www.domain.com Console.WriteLine(info.Port); // 80 Console.WriteLine(page.Port); // 80 (Uri knows the default HTTP port) Console.WriteLine(info.IsBaseOf(page)); // True Uri relative = info.MakeRelativeUri(page); Console.WriteLine(relative.IsAbsoluteUri); // False Console.WriteLine(relative.ToString()); // page.html HttpClient HttpClient class exposes a modern API for HTTP client operations, replacing the old WebClient and WebRequest/WebResponse types HttpClient was written in response to the growth of HTTP-based web APIs and REST services HttpClient HttpClient Example var client = new HttpClient(); string html = await client.GetStringAsync("http://linqpad.net"); To get the best performance with HttpClient, you must reuse the same instance (otherwise things such as DNS resolution can be unnecessarily repeated and sockets are held open longer than necessary). HttpClient permits concurrent operations, so the following is legal and downloads two web pages at once: var client = new HttpClient(); var task1 = client.GetStringAsync("http://www.linqpad.net"); var task2 = client.GetStringAsync("http://www.albahari.com"); Console.WriteLine(await task1); Console.WriteLine(await task2); HttpClient HttpClient properties: Timeout: (request) BaseAddress: which prefixes a URI to every request. Other properties can be passed through HttpClientHandler object HttpClientHandler contains properties to control cookies, automatic redirection, authentication, and so on var handler = new HttpClientHandler { UseProxy = false }; var client = new HttpClient(handler); GetAsync and Response Messages var client = new HttpClient(); // The GetAsync method also accepts a CancellationToken. HttpResponseMessage response = await client.GetAsync("http://..."); response.EnsureSuccessStatusCode(); // Enforce throwing Error for 404 string html = await response.Content.ReadAsStringAsync(); using (var fileStream = File.Create("linqpad.html")) await response.Content.CopyToAsync(fileStream); SendAsync and Request Messages GetAsync, PostAsync, PutAsync, and DeleteAsync are all shortcuts for calling SendAsync SendAsync is the single low-level method into which everything else feeds var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, "http://..."); HttpResponseMessage response = await client.SendAsync(request); response.EnsureSuccessStatusCode();... Instantiating a HttpRequestMessage object means that you can customize properties of the request, such as the headers (see “Headers”) and the content itself, allowing you to upload data. Cookies By default, HttpClient ignores any cookies received from the server. To accept cookies, create a CookieContainer object and assign it an HttpClientHandler: var cc = new CookieContainer(); var handler = new HttpClientHandler(); handler.CookieContainer = cc; var client = new HttpClient(handler); To replay the received cookies in future requests, simply use the same CookieContainer object again. Alternatively, you can start with a fresh CookieContainer and then add cookies manually, as follows: Cookie c = new Cookie("PREF", "ID=6b10df1da493a9c4:TM=1179...", "/", ".google.com"); HttpClient | REST API Methods In a REST API, HTTP methods correspond to CRUD (Create, Read, Update, Delete) operations HttpClient has the following methods to support working with REST API GetAsync: retrieve data or resources from the server PostAsync: create a new resource PutAsync: update a resource or replace it entirely with a new version PatchAsync: partially update a resource (modify only the fields provided) DeleteAsync: delete a resource HttpContent HttpContent is a base class that could be initialized with the following subclases that provides Http content based on a String: StringContent Byte array: ByteArrayContent Stream: StreamContent Container for name/value tuples encoded using application/x-www- form-urlencoded MIME type: FormUrlEncodedContent Uploading Form Data To upload HTML form data, create and populate the FormUrlEncodedContent object. You can then either pass it into the PostAsync method or assign it to a request’s Content property string uri = "http://www.albahari.com/EchoPost.aspx"; var client = new HttpClient(); var dict = new Dictionary { { "Name", "Joe Albahari" }, { "Company", "O'Reilly" } }; var values = new FormUrlEncodedContent(dict); var response = await client.PostAsync(uri, values); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); Free Online REST APIs Here are some free online REST APIs (limited calls) you can use for testing, learning, and experimenting: JSONPlaceholder: Fake online REST API for testing and prototyping (https://jsonplaceholder.typicode.com/) Example endpoints: https://jsonplaceholder.typicode.com/posts OpenWeatherMap: Provides weather data for any location in the world. REST Countries: Get information about countries (https://restcountries.com/) IP Geolocation API: https://ipgeolocation.io/pricing.html , https://apiip.net/get-started Others….. PostAsync Example HttpClient client = new HttpClient(); var data = new { title = "foo #2", body = "what", userId = 7 }; string json = System.Text.Json.JsonSerializer.Serialize(data); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync("https://jsonplaceholder.typicode.com/posts", content); string responseBody = await response.Content.ReadAsStringAsync(); txtPanel.Text = responseBody; Note that you can change the json string of a property by adding [JsonPropertyName(“Json_Name")] before it. Authenticating via Headers | Examples Basic Authentication: HttpClient client = new HttpClient(); byte[] credsBytes = Encoding.UTF8.GetBytes("username:password"); string credentials = Convert.ToBase64String(credsBytes); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",credentials); Bearer Token Authentication: obtain the token from the authentication provider and then add it to the Authorization header as a Bearer token HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerTokenValue); Assignment Design/build a GUI tool to achieve similar tasks as of the following tools PingSweep Tool Tracert Tool REST API CRUD Using (…)