Search MSDN
System.Net Namespace
Namespace: System.Net
The System.Net namespace provides a simple, language-independent, and efficient way to access the most common network protocols. It supports TCP, UDP, HTTP, and FTP, as well as a pluggable protocol model that allows you to incorporate custom protocols.
Overview
This namespace contains classes that provide access to the network functionality of the operating system. You can use these classes to build network-aware applications, send and receive data across networks, and work with various network protocols.
Key features include:
- Support for common Internet protocols like HTTP, FTP, and SMTP.
- Classes for handling network addresses and endpoints.
- Tools for sending and receiving data using TCP and UDP sockets.
- Asynchronous operations for non-blocking network communication.
- Support for secure network communication through SSL/TLS.
Classes
The following classes are key components of the System.Net namespace:
| Class Name | Description |
|---|---|
HttpClient |
Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. |
IPAddress |
Represents an Internet Protocol (IP) address. |
EndPoint |
Abstract base class for network endpoint types. |
Socket |
Provides a low-level network interface for sending and receiving data packets using sockets. |
WebClient |
Provides common methods for sending data to and receiving data from a resource identified by a URI. (Older, but still useful for simple scenarios) |
Uri |
Represents a Uniform Resource Identifier (URI) and provides properties and methods for manipulating or querying the object. |
Enumerations
Useful enumerations in this namespace:
ProtocolType: Specifies the protocol type.SocketType: Specifies the socket type.AddressFamily: Specifies the address family (e.g., IPv4, IPv6).
Interfaces
Key interfaces for advanced network programming:
IWebProxy: Provides support for proxy servers.ISocket: Represents the contract for a socket.
Class: HttpClient
System.Net.Http.HttpClient
The HttpClient class provides a foundation for making HTTP requests. It's recommended for most modern development due to its efficiency and support for asynchronous operations.
Methods
Task<HttpResponseMessage> GetAsync(string requestUri)Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content)Task<HttpResponseMessage> DeleteAsync(string requestUri)
Example: Fetching Data with GET
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class HttpExample
{
public static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/1");
response.EnsureSuccessStatusCode(); // Throws if status code is not 2xx
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
}
}
Class: IPAddress
System.Net.IPAddress
This class represents an IP address, allowing you to work with both IPv4 and IPv6 addresses.
Properties
string AddressFamily: Indicates the address family of the IP address.bool IsIPv4MappedToIPv6: Gets a value indicating whether the IP address is an IPv4-mapped IPv6 address.bool IsIPv6LinkLocal: Gets a value indicating whether the IP address is an IPv6 link-local address.bool IsIPv6Multicast: Gets a value indicating whether the IP address is an IPv6 multicast address.bool IsIPv6SiteLocal: Gets a value indicating whether the IP address is an IPv6 site-local address.bool IsIPv6Teredo: Gets a value indicating whether the IP address is an IPv6 Teredo address.
Static Methods
static IPAddress Parse(string ipString): Parses a string representation of an IP address.static bool TryParse(string ipString, out IPAddress address): Tries to parse a string representation of an IP address without throwing an exception.
Example: Parsing IP Addresses
using System;
using System.Net;
public class IpAddressExample
{
public static void Main(string[] args)
{
IPAddress ipv4Addr = IPAddress.Parse("192.168.1.1");
Console.WriteLine($"Parsed IPv4: {ipv4Addr}");
IPAddress ipv6Addr;
if (IPAddress.TryParse("2001:0db8:85a3:0000:0000:8a2e:0370:7334", out ipv6Addr))
{
Console.WriteLine($"Parsed IPv6: {ipv6Addr}");
}
}
}
Class: Socket
System.Net.Sockets.Socket
Provides a low-level interface for network communication using sockets. Useful for custom protocols or fine-grained control.
Constructors
Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
Methods
void Bind(EndPoint localEP): Associates a local endpoint with the socket.void Listen(int backlog): Puts a listening socket into a state where it can accept incoming connection requests.Socket Accept(): Accepts an incoming connection request.void Connect(EndPoint remoteEP): Establishes a connection to a remote host.int Send(byte[] buffer): Sends data using the connected socket.int Receive(byte[] buffer): Receives data from the connected socket.
Note: Socket programming is complex and often involves managing threads or using asynchronous operations to avoid blocking.