Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
213 views

Fundamentals of Socket Programming

This document provides an overview of socket programming fundamentals in 3 paragraphs or less: The document discusses key data types like unsigned char and unsigned short used in socket programming. It also covers pointers and how they store memory addresses. Structures are introduced as a way to group different data types. Setting up client-server communication with TCP sockets involves initializing sockets, communicating between sockets by establishing connections, sending and receiving data, and closing sockets. The client initiates a connection by calling connect(), while the server listens for connections by calling listen() and accepts connections by calling accept(). Both use send() and recv() to exchange data before closing the connection.

Uploaded by

Luis Clark
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
213 views

Fundamentals of Socket Programming

This document provides an overview of socket programming fundamentals in 3 paragraphs or less: The document discusses key data types like unsigned char and unsigned short used in socket programming. It also covers pointers and how they store memory addresses. Structures are introduced as a way to group different data types. Setting up client-server communication with TCP sockets involves initializing sockets, communicating between sockets by establishing connections, sending and receiving data, and closing sockets. The client initiates a connection by calling connect(), while the server listens for connections by calling listen() and accepts connections by calling accept(). Both use send() and recv() to exchange data before closing the connection.

Uploaded by

Luis Clark
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 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 t(pes are often used in socket
programming:
u_char
u_short
u_long
unsigned )*+it character
unsigned 16*+it integer
unsigned ,*+it integer
- structure is a group of different t(pes 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. 1.2. 3eung
,

% Casting of &ata '(pes
Casting is to change the data t(pe of a
#aria+le or e0pression to the designated one.
/0ample:
% 4f i is an int, then the data t(pe 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:
% *pv gi#es the content stored in the
memor( location $ith address pv.
-ddress operator 6:
% 'he address storing the first memor(
+(te of the #aria+le v is &v.
&r. 1.2. 3eung

%
%


/0ample
% 0 and ( are declared to +e of t(pe
7float7, and p is declared to +e of t(pe
7pointer 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(.
4f x is a one*dimensional arra(,
% the address of the 1st arra( element is
&x[0] or x;
% the address of the ,nd arra( element is
&x[1] or (x+1);
Pointer '(pes
'he )90)6 memor( s(stem is di#ided into
segments, and each segment has 6: ;.
-n address consists of t$o parts: segment
and offset.
&r. 1.2. 3eung
:

Pointer t(pes:
% - near pointer onl( stores the offset $hich is
relati#e to the data segment.
% - far pointer stores +oth the segment and offset.
<(te =rder
% &ifferent computers ma( ha#e different internal
representation of 16 > ,*+it integer (called host byte
order).
% /0amples
<ig*/ndian +(te order (e.g., used +( ?otorola
6)999":
3ittle*/ndian +(te order (e.g., used +( 4ntel
)90)6":
&r. 1.2. 3eung
!

% 'CP>4P specifies a network byte order $hich
is the big-endian +(te order.
% For some 2inSock functions, their arguments
(i.e., the parameters to +e passed to these
functions" 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:
% Protot(pes for these con#ersion functions:
&r. 1.2. 3eung
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 t(pe for generic endpoint address:
% 'CP>4P /ndpoint -ddress
For 'CP>4P, an endpoint address is
composed of the follo$ing items:
% -ddress famil( is AF_INET (-ddress
Family for InterNET).
% /ndpoint address in that famil( is
composed of an IP address and a port
nmber.
&r. 1.2. 3eung
A

'he 4P address identifies a particular
computer, $hile the port num+er identifies a
particular application running on that
computer.
'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 unused
port num+er for it.
% /ach ser#er program must ha#e a pre*
specified port num+er, so that the client
can contact the ser#er.
&r. 1.2. 3eung
)

% 'he port num+er is composed of 16 +its,
and its possi+le #alues are used in the
follo$ing manner:
C 9 * 19,: For $ell*kno$n ser#er
applications.
C 19,: * :D1!1: For user*defined
ser#er applications (t(pical range to
+e used is 19,: * !999".
C :D1!, * 6!!!: For client programs.
% Port num+ers for some $ell*kno$n ser#er
applications:
C 222 ser#er using 'CP: )9
C 'elnet ser#er using 'CP: ,
C S?'P (email" ser#er using 'CP: ,!
C SB?P ser#er using E&P: 161.
&r. 1.2. 3eung
D

% &ata t(pes for 'CP>4P endpoint address:
struct in_addr {
u_long
address */
s_addr ; /* IP
};
C 'he 4P address is stored in a structure
instead of an unsigned long ($ith ,
+its" +ecause of a historical reason.
% so!addr and so!addr"in are compati+le:
% 4f (ou onl( use 'CP>4P, (ou can use
so!addr"in $ithout using so!addr.
&r. 1.2. 3eung

% /0ample 1
C 'he 4P address of a ser#er is
1!).1),.A.6. 4ts decimal #alue is
,66,A,D!!. 2e can specif( the
endpoint address for this ser#er as
follo$s:
struct sockaddr_in ServerAddr;

ServerAddr.sin_family =
AF_INET;
ServerAddr.sin_port = 2000;
ServerAddr.sin_addr.s_addr =
htonl (2662729535);
% /0ample ,
C 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 s(m+olic constant
INA!!"_AN# represents a
$ildcard address that matches an( of
the computerFs 4P address(es".
&r. 1.2. 3eung 19

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. 1.2. 3eung 11

4nitialiHe 2inSock &33
% <efore using 2inSock, an application calls
#$%$tart&p().
C 'hen 2indo$s +inds to the
2inSock &33 and allocates the
necessar( resources to this
application.
% #$%$tart&p() re8uires t$o arguments:
C 'he 1st argument specifies the
#ersion of the re8uested 2inSock.
C 'he ,nd argument returns
information a+out the #ersion of
the 2inSock that is actuall( used.
&r. 1.2. 3eung 1,

% /0ample
#define WSVERS MAKEWORD(2, 0)

WSADATA wsadata ;

WSAStartup ( WSVERS, &wsadata );


&r. 1.2. 3eung 1

Create a Socket
% - program calls so!et() to create a ne$
socket, $hich can then act as the endpoint
of the 'CP connection.
% 'he function so!et() re8uires three
arguments:
C 'he 1st argument is the the protocol
famil(. For 'CP>4P, specif( PFI4B/'
(Protocol Famil( for the 4nterB/'".
C 'he ,nd argument is the t(pe of socket
to +e created. For stream ('CP"
sockets, specif( S=C;IS'R/-?.
C 'he rd argument is simpl( 9.
% 'he call to so!et() returns a socket
descriptor for the ne$l( created socket.
&r. 1.2. 3eung 1:

% /0ample
SOCKET s;

s = socket( PF_INET, SOCK_STREAM, 0 );


&r. 1.2. 3eung 1!

-ssign an /ndpoint -ddress to a Socket
% -fter creating a socket, a ser#er must assign
its endpoint address to this socket.
C 'hen the client can identif( the ser#erFs
socket and send re8uests to this ser#er.
% Steps
C 'he ser#er specifies its endpoint
address. 4n other $ords, it assigns the
follo$ing three attri+ute #alues to a
structure of t(pe sockaddrIin:
protocol famil( (-FI4B/' for 'CP>4P",
4P address,
port num+er.
C 'he ser#er calls 'ind() to +ind its
endpoint address to the ne$l( created
socket.
&r. 1.2. 3eung 16

% /0ample
struct sockaddr_in ServerAddr;

/* Specify the server's endpoint


address in ServerAddr here */

bind ( s, (struct sockaddr *)


&ServerAddr, sizeof(ServerAddr)
);
&r. 1.2. 3eung 1A

% Communicate <et$een Sockets
?ain Steps
% Setup a 'CP connection:
C - client initiates to setup a 'CP
connection to a ser#er.
C 'he ser#er $aits for and accepts
connection re8uests from the clients.
% Send and recei#e data.
% Close the 'CP connection.
4n socket programming, a 'CP connection and
its associated socket are closed simultaneousl(.
'herefore, $e $ill consider the rd step in the
ne0t su+section.
Client 4nitiates a 'CP Connection
% -fter creating a socket, a client calls
onnet() to esta+lish a 'CP connection to a
ser#er.
% 'he function onnet() has three arguments:
C the descriptor of the clientFs socketJ
C endpoint address of the ser#erJ
C length of the ,nd argument.
&r. 1.2. 3eung 1)
);
1D

% /0ample
struct sockaddr_in ServerAddr;

/* Specify the server's endpoint


address in ServerAddr here */

connect ( s, (struct sockaddr


*)&ServerAddr, sizeof(ServerAddr)
&r. 1.2. 3eung

Ser#er 3istens to Connection Re8uests
% -fter creating a socket, the ser#er calls
listen() to place this socket in passi#e
mode.
C 'hen the socket listens and accepts
incoming connection re8uests from
the clients.
% ?ultiple clients ma( send re8uests to a
ser#er.
C 'he function listen() tells the =S to
8ueue the connection re8uests for the
ser#erFs socket.
% 'he function listen() has t$o arguments:
C the ser#erFs socketJ
C the ma0imum siHe of the 8ueue.
% 'he function listen() applies onl( to
sockets used $ith 'CP.
&r. 1.2. 3eung ,9

% /0ample
listen(s, 1);
&r. 1.2. 3eung ,1

Ser#er -ccepts a Connection Re8uest
% 'he ser#er calls aept() to
C e0tract the ne0t incoming
connection re8uest from the 8ueue.
C 'hen the ser#er creates a ne$
socket for this connection re8uest
and returns the descriptor of this
ne$ socket.
% Remarks
C 'he ser#er uses the ne$ socket for
the ne$ connection onl(. 2hen
this connection ends, the ser#er
closes this socket.
C 'he ser#er still uses the original
socket to accept additional
connection re8uests.
C 'he function aept() applies onl(
to stream ('CP" sockets.
&r. 1.2. 3eung ,,

% /0ample
struct sockaddr_in ClientAddr;
int len;
SOCKET nsock;

len = sizeof ( ClientAddr );


nsock = accept( s, (struct
sockaddr *)&ClientAddr, &len );
&r. 1.2. 3eung ,

Send &ata
% <oth client and ser#er calls send() to
send data across a connection.
% 'he function send() copies the outgoing
data into +uffers in the =S kernel, and
allo$s the application to continue
e0ecution $hile the data is +eing sent
across the net$ork.
% 4f the +uffers +ecome full, the call to
send() ma( +lock temporaril( until free
+uffer space is a#aila+le for the ne$
outgoing data.
&r. 1.2. 3eung ,:
,!

% /0ample
char *message="Hello world!";

send(s, message, strlen(message),


0);
&r. 1.2. 3eung

Recei#e &ata
% <oth the client and ser#er call rev() to
recei#e data through a 'CP connection.
% <efore calling rev(), the application
must allocate a +uffer for storing the
data to +e recei#ed.
% 'he function rev() e0tracts the data
that has arri#ed at the specified socket,
and copies them to the applicationFs
+uffer. '$o possi+le cases:
% Case 1: Bo data has arri#ed
C 'he call to rev() +locks until data
arri#es.
% Case ,: &ata has arri#ed
C 4f the incoming data can fit into
the applicationFs +uffer, rev()
e0tracts all the data and returns the
num+er of +(tes recei#ed.
C =ther$ise, rev() onl( e0tracts
enough to fill the +uffer. 'hen it is
necessar( to call rev() a num+er
of times in order to recei#e the
entire message. (See the ne0t
chapter."
&r. 1.2. 3eung ,6

% /0ample: recei#e a small message $ith
at most ! characters
char buf[5], *bptr;
int buflen;

bptr = buf;
buflen = 5;
recv(s, bptr, buflen, 0);
&r. 1.2. 3eung ,A
,)

% Close the Sockets
Close a Socket
% =nce a client or ser#er finishes using a
socket, it calls loseso!et() to
C terminate the 'CP connection
associated $ith this socket, and
C deallocate this socket.
% /0ample
closesocket(s);
&r. 1.2. 3eung

Clean Ep
% 2hen an application finishes using
sockets, it must call #$%(lean&p() to
deallocate all data structures and socket
+indings.
% /0ample
WSACleanup();
&r. 1.2. 3eung ,D

% 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. 1.2. 3eung 9

% Remarks on 2inSock Functions
2inSock has defined some data structures
that can +e used in 2inSock programs.
% /0amples
C so!addr
C so!addr"in
2inSock has defined some s(m+olic
constants that can +e used as arguments to
2inSock functions.
% /0amples
C %)"*+,-
C .)"*+,-
C *+%//0"%+1
C $2(3"$-0,%4 (stream socket"
C $2(3"/50%4 (datagram socket"
'o use these s(m+olic constants and
declarations, include the header file
6inso!.h or 6inso!7.h8
or
#include
#include
<winsock.h>
<winsock2.h>
&r. 1.2. 3eung 1
{

- 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
<stdio.h>
<winsock2.h>
#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. 1.2. 3eung ,
/*

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 the
server */
for (i=0; i<5; ++i){
printf("%c", buf[i]);
}
printf("\n%s\n", "Bye bye!");
/* call closesocket() */
closesocket(s);
/* call WSACleanup() */
WSACleanup();
}
&r. 1.2. 3eung

% Ser#er Program
#include
#include
#define
main()
{
<stdio.h>
<winsock2.h>
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. 1.2. 3eung :

/* 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. 1.2. 3eung !

% 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 call rev() repeatedl( until the
entire message has +een recei#ed. 'he
details are e0plained in the ne0t chapter.
&r. 1.2. 3eung 6

'utorial Pro+lems
% Esing the net$ork +(te order, ho$ is the 4P
address 1!).1),.A.1 stored in the memor(M
% 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
#$%$tart&p() and so!et() for initialiHation.
2hat is the difference +et$een these t$o
functionsM
% 2hen should an application call loseso!et()9
% 2hen should an application call
#$%(lean&p()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 call onnet() M
Should the ser#er call onnet() M
&r. 1.2. 3eung A

% 2hat are the main purposes of listen() M
% 2hat are the main purposes of aept() M
% 4n different e0ecutions of a ser#er, is its port
num+er al$a(s the sameM
% 4n different e0ecutions of a client, is its port
num+er al$a(s 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 calls send() to send a message.
2hen the call returns, does it mean that the
entire message has +een sent outM
% - program calls rev() 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
&r. 1.2. 3eung )

You might also like