Internet Programming - Seneca
Download
Report
Transcript Internet Programming - Seneca
Windows
Programming Using
C#
Internet Programming
Contents
Basic Internet classes
Internet protocols
Client TCP/IP sockets
Server TCP/IP sockets
UDP sockets
2
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
3
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
4
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
5
IPAddress Class
This represents an IP address with
support for IPV6
Methods
byte[]
Returns an array of bytes in the address
string
GetAddressBytes()
ToString()
Returns the address in the usual dotted notation
6
IPAddress Class
Many useful, pre-defined fields are
provided
Any
Matches any IP address
Used for listening to accept any host
Broadcast
An address which sends to all hosts on the local
area network
7
IPAddress Class
Loopback
The loopback address for the local host
None
An address which does not match any real
address
8
Communication Modes
An internet connection is one of two types
Connection-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
9
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
10
Protocols
TCP
Transmission control protocol
Connection-oriented protocol with
guaranteed
delivery
Used for most communication with servers
UDP
User datagram protocol
A connectionless protocol
More efficient than TCP
Used
without guaranteed delivery
for streaming media
11
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.
12
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
13
IPEndPoint Class
Represents one end of a socket
connection
Includes
The
IP address of a computer
A socket number
14
AddressFamily
An enumeration of the types of addressing
that can be used by a socket
Common values include
AppleTalk
InterNetwork
InterNetworkV6
// IPV4
// IPV6
15
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
16
ProtocolFamily
The protocol used by a socket
Raw
Raw protocol
Tcp
Transmission control protocol
Udp
User datagram protocol
17
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);
18
Socket Class
To connect a socket
IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
IPAddress[] addresses = hostEntry.AddressList;
IPEndPoint endPoint = new IPEndPoint(addresses[0],
port);
s.Connect(endPoint);
19
Socket Class
To check to see if the socket is connected
If(s.Connected)
To write data to the socket
s.Send(byte[],
length, offset);
To read from a socket
nread
{…}
= s.Receive(byte[], length, offset);
*see my_curl
20
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
21
TcpListener
To create a server
int port = 2001;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(localAddr, port);
listener.Start();
22
TcpListener
To wait for a connection
Socket
sock = listener.AcceptSocket();
To communicate on a socket
Use
the Send and Receive methods
Close the socket when finished
23
To Connect to a Server
There are two ways
Use
a TcpClient
Create a client and connect
Get a stream to read and write to the server
TcpClient client = new TcpClient(server, port);
NetworkStream stream = client.GetStream();
Read/write the stream
stream.Write(data, 0, data.Length);
Int32 bytes = stream.Read(data, 0, data.Length);
24
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
25
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
26
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);
27
UdpClient
To receive bytes from any computer
IPEndPoint 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
28
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
29
Socket Timeouts
The time is expressed in milliseconds
client.Client.SetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 5000);
When the timeout fires, an exception is
thrown, which must be caught
* see UdpChat
30
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
31
Broadcast
To send a broadcast message use
IPAddress.Broadcast
IPEndPoint remoteIpEnd =
new IPEndPoint(
IPAddress.Broadcast, remotePort);
Send(sendBytes, sendBytes.Length, remoteIpEnd);
32
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?
33
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
34