Windows Programming Using C#
Internet Programming
2
Contents
Basic Internet classes Internet protocols Client TCP/IP sockets Server TCP/IP sockets UDP sockets
3
DNS Class
The DNS class provides a simple interface to the domain name system
This allows you to translate names to IP addresses and vice versa
Remember that a computer with one name might have several IP addresses if it has several network cards
4
DNS Class
Methods IPHostEntry GetHostEntry(string host)
Returns an IPHostEntry for the host The host string can be a host name or a dotted
address If an empty string is passed as the host,
information is returned about the local machine
5
IPHostEntry Class
This holds all the information on a particular host Properties
IPAddress[] AddressList Returns an array of IP addresses for the host If the host cannot be resolved, this list has zero length
string[] Aliases Returns a list of aliases for the host
string HostName Returns the primary name for the host
6
IPAddress Class
This represents an IP address with support for IPV6
Methodsbyte[] GetAddressBytes()
Returns an array of bytes in the address
string ToString() Returns the address in the usual dotted notation
7
IPAddress Class
Many useful, pre-defined fields are providedAny
Matches any IP address Used for listening to accept any host
Broadcast An address which sends to all hosts on the local
area network
8
IPAddress Class
Loopback The loopback address for the local host
None An address which does not match any real
address
9
Communication Modes
An internet connection is one of two typesConnection-oriented
Similar to a phone connection A virtual path is set up between two hosts and the
communication parameters are negotiated Guarantees that the packets are delivered and in
the correct order
10
Communication Modes
Connectionless This is like sending a letter There is no permanent connection between sender
and recipient This saves
Setup time Additional information in the packets to ensure they are
received and in order Connectionless protocols do not guarantee
delivery or delivery in the right order
11
Protocols
TCP Transmission control protocol Connection-oriented protocol with guaranteed delivery Used for most communication with servers
UDP User datagram protocol A connectionless protocol without guaranteed delivery More efficient than TCP Used for streaming media
12
Sockets
The software connection to the internet is called a socket A socket combines
The IP address of a machine A port number
Each program which opens a socket to communicate on the internet uses one of 65,535 sockets on the machine
Data from the network is delivered to a particular socket and then to a particular program listening on that socket
This allows one computer to have many network connections active at once.
13
Sockets
A socket can be of different types TCP/IP
Acts as a data stream between two computers which can be read from and written to
The socket is set up to establish a virtual circuit to a single host
UDP Send discrete messages between computers Each message can be sent to a different computer There is no permanent connection between computers
14
IPEndPoint Class
Represents one end of a socket connection
IncludesThe IP address of a computerA socket number
15
AddressFamily
An enumeration of the types of addressing that can be used by a socket
Common values includeAppleTalk InterNetwork // IPV4 InterNetworkV6 // IPV6
16
SocketType
An enumeration of the types of sockets that can be created
Common values Dgram
Connectionless UDP Raw
Access to underlying protocol Used for ICMP
Stream Connection-oriented TCP/IP
17
ProtocolFamily
The protocol used by a socketRaw
Raw protocol
Tcp Transmission control protocol
Udp User datagram protocol
18
Socket Class
This creates a real socket The namespace is System.Net.Sockets To create a socket
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
19
Socket Class
To connect a socketIPHostEntry hostEntry = Dns.GetHostEntry(hostName);
IPAddress[] addresses = hostEntry.AddressList;
IPEndPoint endPoint = new IPEndPoint(addresses[0], port);
s.Connect(endPoint);
20
Socket Class
To check to see if the socket is connected If(s.Connected) { … }
To write data to the sockets.Send(byte[], length, offset);
To read from a socketnread = s.Receive(byte[], length, offset);
*see my_curl
21
Servers
A server Creates a TcpListener This listens on a particular port for connections When a connection is received, a socket for the
connection is returned Data is exchanged over the socket The socket is closed The listener listens for the next connection
22
TcpListener
To create a server
int port = 2001;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(localAddr, port);
listener.Start();
23
TcpListener
To wait for a connectionSocket sock = listener.AcceptSocket();
To communicate on a socketUse the Send and Receive methodsClose the socket when finished
24
To Connect to a Server
There are two waysUse a TcpClient
Create a client and connect TcpClient client = new TcpClient(server, port);
Get a stream to read and write to the server NetworkStream stream = client.GetStream();
Read/write the stream stream.Write(data, 0, data.Length); Int32 bytes = stream.Read(data, 0, data.Length);
25
To Connect to a Server
Use a Socket Create a normal Socket and connect to the host
and port Use Send and Receive to communicate Close the socket when done
*see hello_client and hello_server
26
UDP
This sends discrete messages rather than a stream of bytes
Each message can be sent to a different computer
UDP is much more efficient than TCP/IP UDP is used for sending audio and video
27
UdpClient
While you can use a socket for UDP communication, it is easier to use a UdpClient
To create a client and listen on a port UdpClient client = new UdpClient(port);
To send bytes to a computer byte[] sendBytes = Encoding.ASCII.GetBytes(msg); client.Send(sendBytes, sendBytes.Length, host,
remotePort);
28
UdpClient
To receive bytes from any computerIPEndPoint remoteIpEndPoint = new IPEndPoint(
IPAddress.Any, 0);Byte[] receiveBytes = client.Receive(ref remoteIpEndPoint);string returnData = Encoding.ASCII.GetString(receiveBytes);
The IPEndPoint passed to Receive is filled in with the address of the sender of the message
To find the message sender remoteIpEndPoint.Address remoteIpEndPoint.Port
29
Socket Timeouts
The Receive call blocks until it receives a message
This can be a problem if nobody wants to talk to you
You can only wait for the phone so long… You need to set a timeout which will
interrupt the receive operation
30
Socket Timeouts
The time is expressed in millisecondsclient.Client.SetSocketOption(
SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
When the timeout fires, an exception is thrown, which must be caught
* see UdpChat
31
Broadcast
Ever feel like just calling anybody? Then broadcast it! A broadcast message will be picked up by
any listener on the local area network Broadcast messages will not pass through
routers
32
Broadcast
To send a broadcast message use IPAddress.BroadcastIPEndPoint remoteIpEnd =
new IPEndPoint(IPAddress.Broadcast, remotePort);
Send(sendBytes, sendBytes.Length, remoteIpEnd);
33
Finding Servers
Normally, servers operate on well-known ports These are ports which are less that 1024 and
are assigned for specific purposes Eg. Web servers are on port 80 This tells us what port the server is on What if we don’t know which machine is hosting
the server?
34
Finding Servers
In this case, we can broadcast for a server Send out a broadcast message to all machines on the
LAN Wait for a reply Use that machine as a server
You can broadcast with UDP on one port to locate the servers
You can then stay with UDP to talk to the servers on another port or switch to TCP/IP on another port