System.Net Namespace
Provides classes for network programming. This namespace includes classes for working with IP addresses, sockets, and HTTP requests.
Classes
-
IPAddress
Represents an Internet Protocol (IP) address.
-
Dns
Provides a simple way to query Domain Name System (DNS) records.
-
Socket
Provides the Windows Sockets API functionality.
-
HttpClient
Sends an HTTP request, as an asynchronous operation, and receives an HTTP response from the resource identified by the URI.
-
NetworkInformation
Provides classes for retrieving network configuration and statistics.
-
Uri
Represents a Uniform Resource Identifier (URI) reference.
-
WebRequest
A base class that provides a common interface for network requests.
-
WebResponse
A base class that provides a common interface for network responses.
-
IPEndPoint
Represents a network endpoint as an IP address and a port number.
Interfaces
-
ICredentials
Defines methods and properties that enable an object to provide credentials for network authentication.
-
ICredentialsCollection
Represents a collection of network credentials.
-
IServerHello
Represents the ServerHello message in an SSL/TLS handshake.
Enumerations
-
SecurityProtocolType
Specifies the protocols that are allowed for transport layer security (TLS) and secure sockets layer (SSL) communications.
-
SocketsFlags
Specifies socket options.
-
IPVersions
Specifies the IP version.
Common Scenarios
The System.Net
namespace is fundamental for building applications that communicate over a network. Some common scenarios include:
- Performing HTTP requests to fetch web content using
HttpClient
orWebRequest
. - Resolving domain names to IP addresses using the
Dns
class. - Working with IP addresses and network endpoints using
IPAddress
andIPEndPoint
. - Creating and managing socket connections for low-level network communication.
Example: Fetching a Web Page
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class WebFetcher
{
public static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
try
{
string url = "https://www.example.com";
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode(); // Throw if the status is not success
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Successfully fetched content from {url}:");
Console.WriteLine(responseBody.Substring(0, Math.Min(responseBody.Length, 500)) + "..."); // Display first 500 chars
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
catch (Exception e)
{
Console.WriteLine($"An unexpected error occurred: {e.Message}");
}
}
}
}