fundamentals of socket programming
TRANSCRIPT
-
8/11/2019 Fundamentals of Socket Programming
1/38
1
Chapter 6
Fundamentals of Socket Programming(Recommended reading: Comer, Vol , Chapter !"
Re#ie$ of C Programming
% Some &ata 'pes
'he follo$ing data tpes are often used in socketprogramming:
u_char
u_short
u_long
unsigned )*+it character
unsigned 16*+it integer
unsigned *+it integer
- structure is a group of different tpes of data.
/0ample:struct info {
char name[20] ;
};
int ID ;
struct info student[60] ;
student[0].name = "chan" ;11
student[0].ID = 1234 ;
student[1].name = "cheung" ;
student[1].ID = 5678 ;
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
2/38
% Casting of &ata 'pes
Casting is to change the data tpe of a
#aria+le or e0pression to the designated one.
/0ample:
% 4f i is an int, then the data tpe of the
follo$ing e0pression is dou+le:
(double) (i+1)
% Pointers
/#er memor location has an address
% 2e can use this address to access the
content in this memor location.
- pointer is a #aria+le that stores the
memory address(not the #alue" of a data
item.
&eclaration of pointer #aria+le:
data-type *pointer-variable;
&ereference operator 5:
%*pvgi#es the content stored in the
memor location $ith addresspv.
-ddress operator :
% 'he address storing the first memor
+te of the #aria+levis&v.
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
3/38
%
%
/0ample
% 0 and are declared to +e of tpe
7float7, and p is declared to +e of tpe7pointer to float7:
float x, y, *p;
'he follo$ing statements
p = &x ;
y = *p ;
are e8ui#alent to
y = x ;Pointer and -rra
'he name of an arra is actuall a pointer
to the first element in the arra.
4fxis a one*dimensional arra,
% the address of the 1st arra element is
&x[0]orx;
% the address of the nd arra element is
&x[1]or(x+1);
Pointer 'pes
'he )90)6 memor sstem is di#ided into
segments, and each segment has 6 ;. -n address consists of t$o parts:segment
andoffset.
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
4/38
Pointer tpes:
% -near pointeronl stores the offset $hich is
relati#e to the data segment.
% -far pointerstores +oth the segment and offset.
*+it integer (calledhost byte
order).
% /0amples
-
8/11/2019 Fundamentals of Socket Programming
5/38
!
% 'CP>4P specifies anetwork byte order$hich
is thebig-endian+te order.
% For some 2inSock functions, their arguments
(i.e., the parameters to +e passed to thesefunctions" must +e stored in net$ork +te order.
% 2inSock pro#ides functions to con#ert +et$een
host +te order and net$ork +te order:
% Prototpes for these con#ersion functions:
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
6/38
6
/ndpoint -ddress% @eneric /ndpoint -ddress
'he socket a+straction accommodates man
protocol families.
% 4t supports man address families.
% 4t defines the follo$ing generic
endpoint address:
%( address family, endpoint address in
that family ) &ata tpe for generic endpoint address:
% 'CP>4P /ndpoint -ddress
For 'CP>4P, an endpoint address is
composed of the follo$ing items:
% -ddress famil isAF_INET(-ddress
FamilyforInterNET).
% /ndpoint address in that famil is
composed of anIP addressand aportnmber.
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
7/38
A
'he 4P address identifies a particularcomputer, $hile the port num+er identifies aparticular application running on thatcomputer.
'he 'CP>4P endpoint address is a special
instance of the generic one:
Port Bum+er
% - port num+er identifies an application
running on a computer.
% 2hen a client program is e0ecuted,
2inSock randoml chooses an unusedport num+er for it.
% /ach ser#er program must ha#e a pre*
specified port num+er, so that the clientcan contact the ser#er.
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
8/38
)
% 'he port num+er is composed of 16 +its,
and its possi+le #alues are used in the
follo$ing manner:
9 * 19: For $ell*kno$n ser#erapplications.
19 * D1!1: For user*defined
ser#er applications (tpical range to
+e used is 19 * !999".
D1! * 6!!!: For client programs.% Port num+ers for some $ell*kno$n ser#er
applications:
222 ser#er using 'CP: )9
'elnet ser#er using 'CP:
S?'P (email" ser#er using 'CP: !
SB?P ser#er using E&P: 161.
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
9/38
D
% &ata tpes for 'CP>4P endpoint address:
struct in_addr {
u_long
address */
s_addr ; /* IP
};
'he 4P address is stored in a structure
instead of an unsigned long ($ith +its" +ecause of a historical reason.
%so!addrandso!addr"inare compati+le:
% 4f ou onl use 'CP>4P, ou can useso!addr"in$ithout usingso!addr.
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
10/38
% /0ample 1
'he 4P address of a ser#er is
1!).1).A.6. 4ts decimal #alue is
66AD!!. 2e can specif theendpoint address for this ser#er asfollo$s:struct sockaddr_in ServerAddr;
ServerAddr.sin_family =
AF_INET;
ServerAddr.sin_port = 2000;
ServerAddr.sin_addr.s_addr =
htonl (2662729535);
% /0ample
2e specif the endpoint address for a
ser#er as follo$s:
struct sockaddr_in ServerAddr;
ServerAddr.sin_family =
AF_INET;
ServerAddr.sin_port = 2000;
ServerAddr.sin_addr.s_addr =
htonl(INADDR_ANY);
$here the sm+olic constant
INA!!"_AN#represents a$ildcard address that matches an ofthe computers 4P address(es".
&r. .2. 3eung 19
-
8/11/2019 Fundamentals of Socket Programming
11/38
Sketch of a 'CP Client and a 'CP Ser#er
% Esing 'CP, +oth the client and the ser#er use
three maGor steps for communication:
4nitialiHe sockets.
Communicate +et$een sockets.
Close the sockets.
% 4n this section, $e stud the a+o#e three steps in
detail.
% Remark
Bet$ork communication ma +e considered
as net$ork 4>=. 'he a+o#e steps are similar
to that for file 4>=:
% =pen a file.
% Read and $rite data.
% Close the file.
% 4nitialiHe Sockets
'here are three initialiHation steps:
% 4nitialiHe 2inSock &33.% Create a socket.
% -ssign an endpoint address to a socket.
&r. .2. 3eung 11
-
8/11/2019 Fundamentals of Socket Programming
12/38
4nitialiHe 2inSock &33
%
-
8/11/2019 Fundamentals of Socket Programming
13/38
% /0ample#define WSVERS MAKEWORD(2, 0)
WSADATA wsadata ;
WSAStartup ( WSVERS, &wsadata );
&r. .2. 3eung 1
-
8/11/2019 Fundamentals of Socket Programming
14/38
Create a Socket
% - program callsso!et()to create a ne$
socket, $hich can then act as the endpoint
of the 'CP connection.% 'he functionso!et()re8uires three
arguments:
'he 1st argument is the the protocol
famil. For 'CP>4P, specif PFI4B/'
(Protocol Famil for the 4nterB/'". 'he nd argument is the tpe of socket
to +e created. For stream ('CP"
sockets, specif S=C;IS'R/-?.
'he rd argument is simpl 9.
% 'he call toso!et()returns a socketdescriptor for the ne$l created socket.
&r. .2. 3eung 1
-
8/11/2019 Fundamentals of Socket Programming
15/38
% /0ample
SOCKET s;
s = socket( PF_INET, SOCK_STREAM, 0 );
&r. .2. 3eung 1!
-
8/11/2019 Fundamentals of Socket Programming
16/38
-ssign an /ndpoint -ddress to a Socket
% -fter creating a socket, a ser#er must assign
its endpoint address to this socket.
'hen the client can identif the ser#ers
socket and send re8uests to this ser#er.
% Steps
'he ser#er specifies its endpoint
address. 4n other $ords, it assigns the
follo$ing three attri+ute #alues to a
structure of tpe sockaddrIin:
protocol famil (-FI4B/' for 'CP>4P",
4P address,
port num+er.
'he ser#er calls'ind()to +ind its
endpoint address to the ne$l created
socket.
&r. .2. 3eung 16
-
8/11/2019 Fundamentals of Socket Programming
17/38
% /0amplestruct sockaddr_in ServerAddr;
/* Specify the server's endpoint
address in ServerAddr here */
bind ( s, (struct sockaddr *)
&ServerAddr, sizeof(ServerAddr)
);
&r. .2. 3eung 1A
-
8/11/2019 Fundamentals of Socket Programming
18/38
% Communicate
-
8/11/2019 Fundamentals of Socket Programming
19/38
);1D
% /0ample
struct sockaddr_in ServerAddr;
/* Specify the server's endpoint
address in ServerAddr here */
connect ( s, (struct sockaddr
*)&ServerAddr, sizeof(ServerAddr)
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
20/38
Ser#er 3istens to Connection Re8uests
% -fter creating a socket, the ser#er calls
listen()to place this socket in passi#e
mode.
'hen the socket listens and accepts
incoming connection re8uests from
the clients.
% ?ultiple clients ma send re8uests to a
ser#er.
'he functionlisten()tells the =S to
8ueue the connection re8uests for the
ser#ers socket.
% 'he functionlisten()has t$o arguments:
the ser#ers socketJ
the ma0imum siHe of the 8ueue.
% 'he functionlisten()applies onl to
sockets used $ith 'CP.
&r. .2. 3eung 9
-
8/11/2019 Fundamentals of Socket Programming
21/38
% /0ample
listen(s, 1);
&r. .2. 3eung 1
-
8/11/2019 Fundamentals of Socket Programming
22/38
Ser#er -ccepts a Connection Re8uest
% 'he ser#er callsaept()to
e0tract the ne0t incoming
connection re8uest from the 8ueue.
'hen the ser#er creates a ne$
socket for this connection re8uest
and returns the descriptor of this
ne$ socket.
% Remarks
'he ser#er uses the ne$ socket for
the ne$ connection onl. 2hen
this connection ends, the ser#er
closes this socket.
'he ser#er still uses the originalsocket to accept additional
connection re8uests.
'he functionaept()applies onl
to stream ('CP" sockets.
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
23/38
% /0ample
struct sockaddr_in ClientAddr;
int len;
SOCKET nsock;
len = sizeof ( ClientAddr );
nsock = accept( s, (struct
sockaddr *)&ClientAddr, &len );
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
24/38
Send &ata
%
-
8/11/2019 Fundamentals of Socket Programming
25/38
!
% /0ample
char *message="Hello world!";
send(s, message, strlen(message),
0);
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
26/38
Recei#e &ata
%
-
8/11/2019 Fundamentals of Socket Programming
27/38
% /0ample: recei#e a small message $ithat most ! characters
char buf[5], *bptr;
int buflen;
bptr = buf;
buflen = 5;
recv(s, bptr, buflen, 0);
&r. .2. 3eung A
-
8/11/2019 Fundamentals of Socket Programming
28/38
)
% Close the Sockets
Close a Socket
% =nce a client or ser#er finishes using a
socket, it callsloseso!et()to
terminate the 'CP connection
associated $ith this socket, and
deallocate this socket.
% /0ample
closesocket(s);
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
29/38
Clean Ep
% 2hen an application finishes using
sockets, it must call#$%leanp()to
deallocate all data structures and socket+indings.
% /0ample
WSACleanup();
&r. .2. 3eung D
-
8/11/2019 Fundamentals of Socket Programming
30/38
% Se8uence of /0ecution of 2inSock Functions
2e assume that 'CP is used and the ser#er
ser#es the clientsK re8uests one after the
other.
Se8uence of e0ecution of 2inSock
functions:
&r. .2. 3eung 9
-
8/11/2019 Fundamentals of Socket Programming
31/38
% Remarks on 2inSock Functions
2inSock has defined some data structures
that can +e used in 2inSock programs.
% /0amples
so!addr
so!addr"in
2inSock has defined some sm+olic
constants that can +e used as arguments to2inSock functions.
% /0amples
%"-
"-
%//"%$23"$-%4(stream socket"
$23"/5%4(datagram socket"
'o use these sm+olic constants and
declarations, include the header file
6inso!.hor6inso!7.h8
or
#include
#include
&r. .2. 3eung 1
-
8/11/2019 Fundamentals of Socket Programming
32/38
{
- Simple and Complete /0ample
% 4n this section, $e implement the follo$ing client*
ser#er application using 'CP:
'he client sends the message 7Lello7 to the
ser#er.
'he ser#er sends this message +ack to the client.
'hen +oth the client and ser#er are terminated.
% Client Program
#include
#include
#define
main()
WSVERS MAKEWORD(2,0)
WSADATA
SOCKET
struct sockaddr_in
char
buf[5],int
wsadata;
s;
ServerAddr;
*message="Hello",
*bptr;i, buflen, count;
/* call WSAStartup() and socket() */
WSAStartup ( WSVERS , &wsadata ) ;
s = socket ( PF_INET , SOCK_STREAM , 0 );
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
33/38
/* call connect() to connect to the server */
ServerAddr.sin_family = AF_INET ;
ServerAddr.sin_port = htons(2000) ;
ServerAddr.sin_addr.s_addr =
htonl(2662729535);connect(s, (struct sockaddr *)
&ServerAddr, sizeof(ServerAddr));
/* call send() to send a message to the
server */
send(s, message, strlen(message), 0);
/* call recv() to receive a message from
the server */
bptr = buf; buflen = 5;
recv(s, bptr, buflen, 0);
/* Echo the received message from theserver */
for (i=0; i
-
8/11/2019 Fundamentals of Socket Programming
34/38
% Ser#er Program
#include
#include
#define
main()
{
WSVERS MAKEWORD(2,0)
WSADATA
SOCKET
struct sockaddr_in
char
int
wsadata;
s, nsock;
ServerAddr,
ClientAddr;
buf[5], *bptr;
i, buflen, count;
/* call WSAStartup() */
WSAStartup ( WSVERS , &wsadata ) ;
/* call socket() */s = socket ( PF_INET , SOCK_STREAM , 0 );
/* call bind() */
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(2000);
ServerAddr.sin_addr.s_addr =
htonl(INADDR_ANY);
bind ( s, (struct sockaddr *) &ServerAddr
, sizeof(ServerAddr) );
/* call listen() */
listen(s,1);
&r. .2. 3eung
-
8/11/2019 Fundamentals of Socket Programming
35/38
/* call accept() */
i = sizeof ( ClientAddr );
nsock = accept (s, (struct sockaddr
*) &ClientAddr , &i );
/* call recv() to receive a message from
the client */
bptr = buf; buflen = 5;
recv ( nsock , bptr , buflen , 0 );
/* call send() to send the message
back to the client */
send ( nsock, buf, strlen(buf), 0);
/* call closesocket() */
closesocket ( nsock );
closesocket ( s );
/* call WSACleanup() */
WSACleanup();
}
&r. .2. 3eung !
-
8/11/2019 Fundamentals of Socket Programming
36/38
% Remarks
For clarit, the a+o#e t$o programs do not
check an possi+le error in net$ork
communication (e.g., $hether the remote
ser#er can +e reached".
% 4n practice, a sophisticated program
should check all the possi+le errors.
4f a program has to recei#e a large message,
it should callrev()repeatedl until the
entire message has +een recei#ed. 'he
details are e0plained in the ne0t chapter.
&r. .2. 3eung 6
-
8/11/2019 Fundamentals of Socket Programming
37/38
'utorial Pro+lems
% Esing the net$ork +te order, ho$ is the 4P
address 1!).1).A.1 stored in the memorM
% State the items in a generic endpoint address.
% State the items in a 'CP>4P endpoint address.
% 2hat is the relationship +et$een the a+o#e t$o
addressesM
% - 2inSock application has to call +oth
#$%$tartp()andso!et()for initialiHation.
2hat is the difference +et$een these t$o
functionsM
% 2hen should an application callloseso!et()9
% 2hen should an application call
#$%leanp()9
% 2hat is the main purpose of'ind()M
% Should a 'CP client call'ind()9
% Should a 'CP ser#er call'ind()9
% Consider a 'CP client*ser#er application.
Should the client callonnet()M
Should the ser#er callonnet()M
&r. .2. 3eung A
-
8/11/2019 Fundamentals of Socket Programming
38/38
% 2hat are the main purposes oflisten()M
% 2hat are the main purposes ofaept()M
% 4n different e0ecutions of a ser#er, is its port
num+er al$as the sameM
% 4n different e0ecutions of a client, is its port
num+er al$as the sameM
% 2hen ou $rite a ser#er program, should ou
assign a port num+er to itM
% 2hen ou $rite a client program, should ou
assign a port num+er to itM
% - program callssend()to send a message.
2hen the call returns, does it mean that the
entire message has +een sent outM
% - program callsrev()to recei#e a message.
2hen the call returns, does it mean that the
entire message has +een recei#edM
% 4f ou $ant to de#elop a ser#er that can store
199 $aiting re8uests, ho$ $ould ou doM