Sie sind auf Seite 1von 55

Chapter 1

Introduction to Sockets
Programming
By
En. Mohd Nizam bin Osman
(Senior Lecturer)
Department of Computer Science
Faculty of Computer and Mathematical Sciences, UiTM Perlis
Course Outline
• Introduction (Network Terminology)
• The Client/Server Paradigm
• Ports
• Sockets
• Addressing
• Sample Server
• Sample Client
• Client/Server Symmetry
• Network Byte Order
• Swapping Byte Order
Introduction
(End System: Computer on the Net)

Internet
(network of
networks)

Also known as a “host”


Figure 1: Fundamental devices on the Internet
Introduction
(End System: Computer on the Net)
A host (also known as "network host") is a computer or
other device that communicates with other hosts on a
network.

Hosts on a network include clients and servers -- that


send or receive data, services or applications.
Introduction
(End System: Computer on the Net)

The basic unit of communication on the Internet is the


packet.

Packet is made up of a payload, which contains the


data to be communicated, and a header, which
describes the payload and includes information about
the sender and intended receiver of the data.
Introduction
(Computer Network)
A computer network is a set (two or more) of
connected computers that share data/support
communication between them.
Computers on a network are called nodes.

Computer Network
Introduction
(Computer Network)
The connection between computers can be done via
cabling, most commonly the Ethernet cable, or
wirelessly through radio waves.

Connected computers can share resources, like access


to the Internet, printers, file servers, and others.
Introduction
(Computer Network)
Network evolution
Centralized (mainframe) models
Client/server models
Web-based networking
Mainframe

Terminal Terminal Terminal Terminal

Mainframe Client-Server
Introduction
(Network Applications)
Network Application are everywhere.

E-mail Real-time video


Web Browser
conferencing

Streaming stored
video clips Multi user
networked game
Introduction
(Types of Communication)
• Allowing a stream of bytes to flow bidirectionally

Stream •


No framing in communication
Reliable.
Example: TCP and SCTP

• Messages are sent from a source and a destination, without any connection setup

Datagram • Unreliable
• Example: UDP

• Communication between all entities on a network

Broadcast • Based upon the datagram mode


• Example: can be performed using UDP

• Permits the creation of a group of receivers on a network, for which a sender can

Multicast transmit a message to single address (the group), but all the receivers in the group
receive the message.
• Example: UDP-based.
Network Entities
Types of devices found on the Internet:
Host • Basic edge device on the Internet

Host • A specialized device that provides


Bridges protocol-independent routing of
datagrams
Bridges
• A specialized application that may run
Device Routers
a particular version of an IP stack to
s route datagrams between two or more
network
Router
• Device provides the highest level of IP
routing as it commonly inspects
Gateways
Gateways datagram packet headers in the
transport header
Introduction
(Client)
A client is a computer that retrieves information from or
uses resources provided by the server or main
computer.
Introduction
(Server)
In a technical sense, a server is an instance of a
computer program that accepts and responds to
requests made by another program, known as a client.
Less formally, any device that runs server software
could be considered a server as well.
Servers are used to manage network resources. For
example, a user may setup a server to control access
to a network, send/receive e-mail, manage print jobs, or
host a website.
Introduction
(Server)
Varieties type of server:
 Application server
 Blade server
 Cloud server
 Database server
 Dedicated server
 File server
 Print server
 Proxy server
 Standalone server
 Web server
Introduction
(Client-Server Functions)
The main Managing the user interface
operations
of the
client Accepts and checks the syntax of user inputs
system:
Processes application logic

Generates database request and transmits to


server
Passes response back to server.
Introduction
(Client-Server Functions)
The main Accepts and processes database requests from client.
operations
of the Checks authorization
server
system: Ensures that integrity constraints are not violated

Performs query/update processing and transmits

Maintains system catalogue

Provide concurrent database access

Provides recovery control


Introduction
(Client-Server Topologies)
Refers to the physical layout of client/server network in
which all the clients and servers are connected to each
other.

There are three topologies:


1. Single client, single server
2. Multiple clients, single server
3. Multiple clients, multiple servers.
Introduction
(Client-Server Topologies)
1. Single client, single server
• One client is directly connected to one server.

Client Server
Introduction
(Client-Server Topologies)
2. Multiple clients, single server
• Several clients are directly connected to only one server.

Client 1

Server

Client 2
Introduction
(Client-Server Topologies)
3. Multiple clients, multiple servers
 Several clients are directly connected to several servers.

Client 1
Server 1

Client 2

Client 3 Server 2
Introduction
(Client-Server Programming Model)
1. Client sends request
Client Server
process process Resource
2. Server Processes
4. Client request
3. Server sends response
processes
response
Client-Server transaction

 Every network application based on the client-server model.


 An application consists of:
1. Server
2. Client
 A server manages some resources, and it provides some service for its
clients by manipulating resource.
Introduction
(Client-Server Programming Model)
A client-server transaction consists of four steps:
When a client needs service, it initiates a transaction by
sending a request to the server.

The server receives the request, interpret it, and


manipulates its resources in the appropriate way.

The server send a response to the client, and then waits


for the next request.

The client receives the response and manipulates it.


Introduction
(Network Programming)
The term network programming refers to writing
programs that execute across multiple devices
(computers), in which the devices are all connected to
each other using a network.
PACKET
All modern computer networks are packet-switched
networks: data traveling on the network is broken into
chunks called packets and each packet is handled
separately.
Each packet contains information about who sent it and
where it's going.
PROTOCOL
A protocol is a precise set of rules defining how
computers communicate over the socket: the format of
addresses, how data is split into packets, and so on.
There are many different protocols defining different
aspects of network communication.
Example:
 TCP – is a stream-based reliable protocol
 UDP – is a datagram (message)-based that can be
unreliable.
Ports
An IP address identifies a host machine on the Internet.
Each computer with an IP address has several
thousand logical ports.
An IP port will identify a specific application running on
the Internet host machine
A port is identified by a number, the port number
Each port is identified by a number between 1 and
65,535. Each port can be allocated to a particular
service.
Ports
There are some common port numbers which are
dedicated for specific application:
Applications Port numbers
HTTP 80
FTP 20 and 21
Gopher 70
SMTP (e-mail) 25
POP3 (e-mail) 110
Telnet 23
Finger 79
Sockets
Sockets allow communication between two different
processes on the same or different machines.
The application creates a socket
The socket type dictates the style of communication
reliable vs. best effort
connection-oriented vs. connectionless
Once configured, the application can:
pass data to the socket for network transmission.
receive data from the socket (transmitted through the
network by some other host).
Sockets
Where is Socket Used?
• Used in a client-server application framework. A server
is a process that performs some functions on request
from a client.

• Most of the application-level protocols like FTP, SMTP,


and POP3 make use of sockets to establish connection
between client and server and then exchanging data.
Sockets
(Socket Types)
Four types of socket available to the users:
• Delivery in a networked environment is
guaranteed.
• These sockets used TCP (Transmission
Stream Control Protocol) for data transmission.
Sockets • If delivery is impossible, the sender
receives an error indicator.
• Data records do not have any boundaries.
• Delivery in a networked environment is not
Datagram guaranteed.
Sockets • Use UDP (User Datagram Protocol).
Sockets
(Socket Type)
Four types of socket available to the users:
• Provide users access to underlying communication
protocols, which support socket abstraction.
Raw • Normally datagram oriented.
Sockets • Not intended for the general user
• Mainly for those interested in developing new
communication protocols.
• Similar to stream socket, with the exception that
Sequenced record boundaries are preserved.
Packet • Allow the user to manipulate the Sequence Packet
Sockets Protocol (SPP) or Internet Datagram Protocol (IDP)
headers on a packet or a group of packets.
Sockets
 Where is the socket programming interface in relationship to the
IP protocol stack?
7 Application

6 Presentation Application
Socket API
5 Session

4 Transport TCP UDP

3 Network IPv4,IPv6

2 Datalink
Device Driver
and Hardware
1 Physical
OSI Model Internet Protocol (IP) Suite
Sockets
(Primary Socket Function)
The basic network I/O functions for a Linux system.
P r im a r y S o c k e t F u n c tio n s
O P E R A T IO N E X P L A N A T IO N

O pen P re p a re fo r in p u t o r o u tp u t o p e ra tio n s.

C lo se S to p p re v io u s o p e ra tio n s a n d re tu rn re s o u rc e s.

R ead G e t d a ta a n d p la c e in a p p lic a tio n m e m o ry.

W rite P u t d a ta fro m a p p lic a tio n m e m o ry a n d s e n d c o n tro l.

C o n tro l (io c tl) S e t o p tio n s s u c h a s b u ff e r s iz e s a n d c o n n e c tio n b e h a v io r.


Addressing
The IP host address (IP address) is used to identify
host connected to the Internet.
IP stands Internet Protocol and refers to the Internet
Layer of the overall network architecture of the Internet.
An IP address is a 32-bits long (ex: IPv4 address) are
broken into 4 octets, or 8 bits fields (0 – 255 value in
decimal notation).
Each IP address uniquely identifies the participating
user network, the host on the network, and the class of
the user network.
Addressing
An IP address is usually written as an decimal integer
value (0-255) and separated by a dot of the form:
N1.N2.N3.N4
For example:
138.23.44.2
IP address is represented by a domain name,
for example: uitm.edu.my
Addressing
(Address Classes)
There are five different address classes:
Addressing
(Address Classes)
There are five different address classes:
1. Class A – addresses begin with 0xxx, or 1 to 127 decimal
2. Class B - addresses begin with 10xx, or 128 to 191
decimal
3. Class C - addresses begin with 110x, or 192 to 223
decimal
4. Class D - addresses begin with 1110, or 224 to 239
decimal
5. Class E - addresses begin with 1111, or 240 to 254
decimal
Addressing
(Address Classes)
Class D – addresses are reserved for multicasting
Class E – addresses are reserved for future use.
They should not be used for host addresses.
Sample Server
A server usually consists of a sequence of system calls
to perform the following tasks:
1. Allocate a communication channel (passive socket).
2. Bind the socket to a port number (for clients to make
connection to).
3. Inform the operating system of any relevant parameters
needed.
4. Loop, waiting for incoming connections
5. Process each connection.
Sample Server
(Source Code – Daytime protocol server)
1 #include <sys/socket.h>
2 #include <arpa/inet.h>
3 #include <stdio.h> Header file
4 #include <time.h>
5 #include <unistd.h>
6
7 #define MAX_BUFFER 128
Max buff size
8 #define DAYTIME_SERVER_PORT 13 & port no.
9
10 int main ( void )
11 {
12 int serverFd, connectionFd;
13 struct sockaddr_in servaddr;
14 char timebuffer[MAX_BUFFER+1];
15 time_t currentTime;
16
17 serverFd = socket(AF_INET, SOCK_STREAM, 0); Create a new socket
18
19 memset(&servaddr, 0, sizeof(servaddr));
20 servaddr.sin_family = AF_INET;
Initialize a new
21 servaddr.sin_addr.s_addr = htonl(INADDR_ANY); socket
22 servaddr.sin_port = htons(DAYTIME_SERVER_PORT);
23
Sample Server
(Source Code – Daytime protocol server)
24
25
bind(serverFd,
(struct sockaddr *)&servaddr, sizeof(servaddr));
Configure the
26
Permit connections socket
27 listen(serverFd, 5);
28 to be made
29
30
while ( 1 ) {
Accept incoming
31
32
connectionFd = accept(serverFd,
(struct sockaddr *)NULL, NULL);
connection
33
34
35
if (connectionFd >= 0) {
Handles incoming
36
37
currentTime = time(NULL);
snprintf(timebuffer, MAX_BUFFER, "%s\n",
connection
38 ctime(&currentTime));
39 Send data to
40 write(connectionFd, timebuffer, strlen(timebuffer));
41 client
42 close(connectionFd);
43
44 }
Close the new
45 client socket
46 }
47
48 }
Sample Client
A client usually consists of a sequence of system calls
to perform the following tasks:
1. Allocate a communication channel (active socket).
2. Connect the socket to a port number and host where the
desired service resides.
3. Wait for the connection to complete and check for failure.
4. Perform the task.
5. Disconnect and clean up if necessary.
Sample Client
(Source Code – Daytime protocol client)
1 int main ( )
2 {
3 int connectionFd, in;
4 struct sockaddr_in servaddr;
5 char timebuffer[MAX_BUFFER+1];
6
7 connectionFd = socket(AF_INET, SOCK_STREAM, 0);
8
9 memset(&servaddr, 0, sizeof(servaddr));
10 servaddr.sin_family = AF_INET;
11 servaddr.sin_port = htons(DAYTIME_SERVER_PORT);
12
13 servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
Address of the
14
Host (loopback)
Sample Client
(Source Code – Daytime protocol client)
15 connect(connectionFd, Connection to
16 (struct sockaddr_in *)&servaddr, server
17 sizeof(servaddr));
18
19 while ( (in = read(connectionFd, timebuffer,
20 MAX_BUFFER)) > 0) {
21
Read from a
22 timebuffer[in] = 0; socket
23 printf("\n%s", timebuffer);
24
25 }
26
27 close(connectionFd);
28
29 return(0);
30 }
Client/Server Symmetry
Server

socket()

Client bind()

socket() listen()

Establish
connect() accept()
connection

read() Data write()


transfer

close() close()
Client/Server Symmetry
(Description)
The server must create a socket (using the socket
call)
Then name it (using bind) so that clients can reference
it.
The listen call makes the server visible and allows it
to accept connections.
The server then must use the accept call to accept
incoming client connections, which are represented by
a newly created socket representing the new endpoint.
Client/Server Symmetry
(Description)
For client to connect to the server, it must also create a
socket. Additionally, we must define for the socket what
we want to connect to. This is defined in the
sockaddr_in structure.
Then by using connect call, we cause the three-way
handshake to occur between the client and server,
(using in this case TCP).
The relationship between connect and accept. The
accept call defines the server’s willingness to
communicate, whereas the connect call defines the
client’s desire to communicate.
Client/Server Symmetry
(Description)
For the write and read calls, the same symmetry exists.
There’s no point calling the read function if the peer
never writes any additional data into the socket.
Closing socket also illustrate some symmetry. When
application performs a close, it define intent not to send
any additional data through the socket.
Network Byte Order
Ports and addresses are always specified in calls to the
socket functions using the network byte order
convention.
Network Byte Order refers to how bytes are arranged
when sending data over a network.
Two common format:
1. Little endian - byte ordering places the least
significant byte first.
2. Big endian - byte ordering places the most
significant byte first.
Network Byte Order
1. Little endian - byte ordering places the least
significant byte first.
Address 101 102 103 104
Contents 11 22 33 44

2. Big endian - Byte ordering places the most


significant byte first.
Address 101 102 103 104
Contents 44 33 22 11
Network Byte Order
(Example)
32-bits Number: 0x44332211

Four-Byte Integer: 0x44332211


Memory Address Big Endian byte Little-Endian byte
value value
101 44 11
102 33 22
103 22 33
104 11 44

The “little” end byte, the lowest or least significant byte, is 0x11.
The “big: end byte, the highest or most significant byte, is 0x44
Network Byte Order
The values stored in the packet headers are in big
endian format.
Processors that utilized big endian (Motorola/IBM
mainframe/ Sun SPARC…) required no byte-swapping
to occur.
Processors that utilized little endian (Intel/AMDx86…)
required all packet fields of more than one byte to be
swapped from little endian to big endian
The lack of byte swapping to convert from host byte
order to network byte order can lead slight performance
advantage.
Swapping Byte Order
 Problem:
different machines/OS’s use different word orderings
little-endian: lower bytes first
big-endian: higher bytes first
 These machines may communicate with one another over the
network:
Host Byte-Ordering: the byte ordering used by a host (big or little)
Network Byte-Ordering: the byte ordering used by the network – always
big-endian
 Any words sent through the network should be converted to
Network Byte-Order prior to transmission (and back to Host
Byte-Order once received)
Swapping Byte Order
 The sockets API provides four functions to swap the byte order
of fundamental types:
1. nthohs (network-to-host-short)
2. htons (host-to-network-short)
3. nthohl (network-to-host-long)
4. htonl (host-to-network-long)
 Operate on two basic types:
1. Short ( 16-bit words)
2. Longs (32-bit words)
 A function is provided for both converting to network byte order
(from host byte order) and converting to host byte order (from
network byte order)
The End
Q&A

Das könnte Ihnen auch gefallen