Socket programming Tasos Alexandridis 1HY335a - Socket Programming.
Socket Programming Basics
-
Upload
miraclesuresh -
Category
Documents
-
view
227 -
download
0
Transcript of Socket Programming Basics
-
8/9/2019 Socket Programming Basics
1/69
Sockets Part 2
-
8/9/2019 Socket Programming Basics
2/69
-
8/9/2019 Socket Programming Basics
3/69
struct sockaddr
{
unsigned short sa_family; /* Address family (e.g., AF_IN!" */
char sa_data#$%&; /* 'rotocols)ecific address information */
;
struct sockaddr_in
{
unsigned short sin_family; /* Internet )rotocol (AF_IN!" */
unsigned short sin_)ort; /* 'ort ($+its" */
struct in_addr sin_addr; /* Internet address (-its" */
char sin_ero#0&; /* Not used */;
struct in_addr
{
unsigned long s_addr; /* Internet address (-its" */
;
Generic
IP
Specifc
sockaddr
sockaddr_in
Family
Family Port
Blob
Internet address Not used
2 bytes 2 bytes 4 bytes 8 bytes
-
8/9/2019 Socket Programming Basics
4/69
-
8/9/2019 Socket Programming Basics
5/69
A socket address structures is alays passed by re!erence "enpassed as an ar#ument to any socket !unctions$ But any socket!unction t"at takes one o! t"ese pointers as an ar#ument mustdeal it" socket address structures !rom any o! t"e supportedprotocol !amilies$
-
8/9/2019 Socket Programming Basics
6/69
%"e IP&' socket address is defned by includin# t"e (netinet)in$"*
"eader
-
8/9/2019 Socket Programming Basics
7/69
+%"e SIN',-.N constant must be defned i! t"e system supports t"e
len#t" member !or socket address structures$
+%"e IP&' !amily is AF,IN.%'/ "ereas t"e IP&4 !amily is AF,IN.%$
+%"e members in t"is structure are ordered so t"at i! t"esockaddr,in' structure is '40bit ali#ned/ so is t"e 1280bit sin',addr
member$ n some '40bit processors/ data accesses o! '40bit &aluesare optimi3ed i! stored on a '40bit boundary$
+%"e sin',oin!o member is di&ided into to felds5+%"e lo0order 26 bits are t"e o label+%"e "i#"0order 12 bits are reser&ed
+%"e sin',scope,id identifes t"e scope 3one in "ic" a scopedaddress is meanin#!ul/ most commonly an inter!ace inde7 !or a link0local address
-
8/9/2019 Socket Programming Basics
8/69
A ne #eneric socket address structure as defned as part o! t"e IP&'
sockets API/ to o&ercome some o! t"e s"ortcomin#s o! t"e e7istin# structsockaddr$ nlike t"e struct sockaddr/ t"e ne struct sockaddr,stora#e islar#e enou#" to "old any socket address type supported by t"e system$
%"e sockaddr,stora#e structure is defned by includin# t"e (netinet)in$"*"eader
-
8/9/2019 Socket Programming Basics
9/69
%"e sockaddr,stora#e type pro&ides a #eneric socket addressstructure t"at is di9erent !rom struct sockaddr in to ays5
a$I! any socket address structures t"at t"e system supports "a&eali#nment re:uirements/ t"e sockaddr,stora#e pro&ides t"estrictest ali#nment re:uirement$
b$%"e sockaddr,stora#e is lar#e enou#" to contain any socketaddress structure t"at t"e system supports$
-
8/9/2019 Socket Programming Basics
10/69
-
8/9/2019 Socket Programming Basics
11/69
11
Net1ork 'rogramming issues
Byte Ordering Naming
Addressing
-
8/9/2019 Socket Programming Basics
12/69
12
2yte 3rdering of Integers
Different CPU architectures have different byte
ordering
D3
high-order byte low-order byte
memory
address A
memory
address A !
Stored at little0endiancomputer
Stored at bi#0endiancomputer
low-order byte high-order byte
"#Inte#er representation ;2byteessa#e in >emory o!o! bi#0endian?omputer
>essa#e is sentacross Netork 48 4@ 4? 4? 'F 61
66
>essa#e is5ello/1C
>essa#e is5ello/@12C
Pro c e s s i
n#
48 4@ 4? 4? 'F 61
66
>essa#e in >emory o!little0endian?omputer P
ro c e s s
in#
Anser5
Not"in# i! t"ey do not e7c"an#e inte#ersD
But5 I! t"ey e7c"an#e inte#ers/ t"ey ould #et t"eron# order o! bytes/ t"ere!ore/ t"e ron# &alueD
.7ample5
-
8/9/2019 Socket Programming Basics
14/69
14
2yte 3rdering 4olution )here are two solutions if com'uters with different byte
ordering system want to communicate )hey must *now the *ind of architectureof the sending
com'uter+bad solution, it has not been im'lemented
.ntroduction of a networ* byte order +big-endian/ )he functions
are%uint16_t htons(uint16_thost16bitvalue)
uint32_t htonl(uint32_t host32bitvalue)
uint16_t ntohs(uint16_t net16bitvalue)uint32_t ntohs(uint32_t net32bitvalue) Note% use for all integers +short and long, which
are sent across the networ*
.ncluding 'ort numbers and .P addresses
-
8/9/2019 Socket Programming Basics
15/69
Networ* Byte Order
# if __BYTE_ORDER == __BIG_ENDIAN
/* The host byte order is the same as netor! byte order"
so these fn$tions are a%% &st identity' */
# define ntoh%() ()
# define ntohs() ()
# define hton%() ()
# define htons() ()
# e%se# if __BYTE_ORDER == __+ITT+E_ENDIAN
# define ntoh%() __bsa,_-. ()
# define ntohs() __bsa,_0 ()
# define hton%() __bsa,_-. ()
# define htons() __bsa,_0 ()
# endif
# endif
#in$%de 1netinet/in'h2
int0_t htons(int0_t host0bit3a%e4int-._t hton%(int-._t host-.bit3a%e4int0_t ntohs(int0_t net0bit3a%e4int-._t ntoh%(int-._t net-.bit3a%e4
-
8/9/2019 Socket Programming Basics
16/69
Program to determine host byte order
-
8/9/2019 Socket Programming Basics
17/69
Byte 0ani'ulation "unctions# grou's of functions o'erate on multibyte fields
can1t rely on C convention of null-terminated string, since
data can contain 2eros +e/g .P addresses
operate on multibyte felds/ it"out interpretin# t"edata/ and it"out assumin# t"at t"e data is a null0
terminated ? strin#need t"ese types o! !unctions "en dealin# it"socket address structures because e need tomanipulate felds suc" as IP addresses
-
8/9/2019 Socket Programming Basics
18/69
Byte 0ani'ulation functions4#include
void bzero(void *dest, size_t nbtes)! "*zeros nbtes
void bco(const void *src, void *dest, size_tnbtes)!
int bc$(const void *tr1, const void *tr2,
size_t nbtes)!5eturns% 6 if e7ual, non2ero if une7ual
void* $e$set(void *dest, int c, size_t len)!
void* $e$c(void *dest, const void *src, size_tnbtes)!
int $e$c$(const void *tr1, const void *tr2,size_t nbtes)!
5eturns% 6 if e7ual, 86 or 96 if une7ual
-
8/9/2019 Socket Programming Basics
19/69
1E
Naming and Addressing
:ost name identifies a single host +Domain Name ;ystem variable length string+e/g/ www/ber*eley/edu is ma''ed to one or more .P addresses
.P Address written as dotted octets +e/g/ !6/6/6/! 3# bits/ Not a number< But often needs to be
converted to a 3#-bit to use/ Port number
identifies a 'rocess on a host != bit number
-
8/9/2019 Socket Programming Basics
20/69
inet>aton, inet>addr and
inet>ntoa Convert internet addresses between
A;C.. strings and networ* byte ordered
binary values inet>aton, inet>ntoa and inet>addr convert
an .'v? address from a dotted-decimal
string +e/g/ @#6=/!=/!!#/= to its 3#-bit
networ* byte ordered binary value
Newer functions inet>'ton and inet>nto'
handle both .Pv? and .Pv= addresses/
-
8/9/2019 Socket Programming Basics
21/69
IPv4 Address Conversion Functions
include (arpa)inet$"*
int inet,aton;const c"ar strptr/ struct in,addr addrptr
-
8/9/2019 Socket Programming Basics
22/69
IPv4 IPv! Address Conversion Functions
inet_"tonand inet_nto"Functionsinclude (arpa)inet$"*
int inet,pton;int !amily/ const c"ar strptr/ &oid addrptr
-
8/9/2019 Socket Programming Basics
23/69
#ummary o0 address conversion 0unctions
-
8/9/2019 Socket Programming Basics
24/69
#ock_nto" Function
inet,ntopis t"at it re:uires t"e caller to pass a pointer to a binary addret"e caller to kno t"e !ormat o! t"e structure and t"e address !amily
sock,ntopt"at takes a pointer to a socket address structure/ looks inside t"e struct
and calls t"e appropriate !unction to return t"e presentation !ormat o! t"e address$
include Lunp$"L
c"ar sock,ntop;const struct sockaddr sockaddr/ socklen,taddrlen
-
8/9/2019 Socket Programming Basics
25/69
readn/ riten/ and readlineFunctions
include Lunp$"L
ssi3e,t readn;int fledes/ &oid bu9/ si3e,t nbytes
-
8/9/2019 Socket Programming Basics
26/69
2'
Other useful functions
gethostname+char name, int len%gets the name of thecurrent host gethostbyaddr+char addr, int len, int ty'e%converts .P
hostname to structure containing long integer gethostbyname+const char name);
getaddrinfo() & getnameinfo() work with IPv6 as well better to use these
int getsoc*name+int socket, struct soc*addr restrictaddress, soc*len>t restrict address_lenE
&arning% chec* function assum'tions about byte-ordering
+host or networ*/ Often, they assume 'arameters F returnsolutions in networ* byte-order
-
8/9/2019 Socket Programming Basics
27/69
2M
Issues in ?lient)Ser&er
Pro#rammin#
-
8/9/2019 Socket Programming Basics
28/69
28
.ssues in Client Programming .dentifying the ;erver/
Goo*ing u' a .P address/
Goo*ing u' a well *nown 'ort name/
;'ecifying a local .P address/
UDP client design/ )CP client design/
-
8/9/2019 Socket Programming Basics
29/69
2E
.dentifying the ;erver O'tions%
hard-coded into the client 'rogram/
re7uire that the user identify the server/
read from a configuration file/
use a se'arate 'rotocolFnetwor* service to
loo*u' the identity of the server/
-
8/9/2019 Socket Programming Basics
30/69
-
8/9/2019 Socket Programming Basics
31/69
=1
;ervices and Ports 0any services are available via @well
*nown addresses +names/
)here is a ma''ing of service names to
'ort numbers%struct *servent getservbna$e( char *service,
char *rotocol )!
servent-9s>'ort is the 'ort number in
networ* byte order/
-
8/9/2019 Socket Programming Basics
32/69
=2
;'ecifying a Gocal Address &hen a client creates and binds a
soc*et it must s'ecify a local 'ort and
.P address/ )y'ically a client doesnHt care what 'ort
it is on%
haddr%>ort & htons(')!
give me any avai2ab2e "ort give me any avai2ab2e "ort
-
8/9/2019 Socket Programming Basics
33/69
==
Gocal .P address A client can also as* the o'erating system
to ta*e care of s'ecifying the local .P
address%
haddr%>sin_addr.s_addr&
htonl(++_-)!
5ive me the a""ro"riate address5ive me the a""ro"riate address
-
8/9/2019 Socket Programming Basics
34/69
=4
UDP Client Design Istablish server address +.P and 'ort/
Allocate a soc*et/
;'ecify that any valid local 'ort and .P
address can be used/
Communicate with server +send, recv
Close the soc*et/
-
8/9/2019 Socket Programming Basics
35/69
=@
Connected mode UDP A UDP client can call connect+ to
establish the address of the server/
)he UDP client can then use read+ andwrite+ or send+ and recv+/
A UDP client using a connected mode
soc*et can only tal* to one server+using the connected-mode soc*et/
-
8/9/2019 Socket Programming Basics
36/69
='
)CP Client Design Istablish server address +.P and 'ort/
Allocate a soc*et/
;'ecify that any valid local 'ort and .P
address can be used/
Call connect+
Communicate with server +read,write/
Close the connection/
-
8/9/2019 Socket Programming Basics
37/69
=M
Closing a )CP soc*et 0any )CP based a''lication 'rotocols
su''ort multi'le re7uests andFor
variable length re7uests over a single)CP connection/
:ow does the server *now when the
client is done +and it is OJ to close thesoc*et (
-
8/9/2019 Socket Programming Basics
38/69
=8
Partial Close One solution is for the client to shut
down only itHs writing end of the soc*et/
)he shutdown+ system call 'rovidesthis function/
shutdown( int s, int direction);
direction can be 6 to close the reading endor ! to close the writing end/
shutdown sends info to the other 'rocess.ASO % PGA>
+transport protocol "andles t"e tou#"transport protocol "andles t"e tou#"stu9$stu9$
+re:uires separate socket !or eac"re:uires separate socket !or eac"connection$connection$?onnectionless?onnectionless
+less o&er"eadless o&er"ead+no limitation on number o! clientsno limitation on number o! clients
-
8/9/2019 Socket Programming Basics
46/69
Connectionless .terative
server Uses connectionless 'rotocol% UDP/ ;erver 'rocesses one re7uest at a time/
;erver uses one single 'ort Lwell-*nown 'ortM
-
8/9/2019 Socket Programming Basics
47/69
Connection oriented concurrent server
-
8/9/2019 Socket Programming Basics
48/69
Connection-oriented concurrent server
Uses connection-oriented% )CP At first connection is established/ Uses one well-*nown 'ort and many e'hemeral 'orts
;erver issues 'assive-o'en at well-*nown 'ort/ Client initially a''roaches this 'ort/ After connection is made, server assigns a tem'orary 'ort to free
the well-*nown 'ort/ Data transfer via e'hemeral 'ort/
-
8/9/2019 Socket Programming Basics
49/69
4E
Concurrent ;erver
Design AlternativesOne child 'er client
;'awn one thread 'er client
Prefor*ing multi'le 'rocesses
Prethreaded ;erver
-
8/9/2019 Socket Programming Basics
50/69
@6
One child 'er client )raditional UniK server% )CP% after call to accet(),call or/().
UDP% after readro$(),call or/(). Iach 'rocess needs only a few soc*ets/
;mall re7uests can be serviced in a small
amount of time/
Parent 'rocess needs to clean u' after
children
-
8/9/2019 Socket Programming Basics
51/69
"or* and eKec functions
Need to create a new child 'rocess tohandle each incoming client
re7uestFtransaction
for* function is the only way in UniK to
create a new 'rocess%
#in$%de 1nistd'h2
,id_t for!(3oid4
5eturns% 6 in child, 'rocess .D of child in 'arent, -! on error Called once but returns !5I6
3nce in the )arent )rocess (returns child )rocess id", and once in the child )rocess (return of 7"
-
8/9/2019 Socket Programming Basics
52/69
0ore "or*ing
All descri'tors o'en in the 'arent before
the call to for*+ are shared with the
child after for* returns/ .ncluding the connected soc*et file
descri'tion returned by acce't
-
8/9/2019 Socket Programming Basics
53/69
-
8/9/2019 Socket Programming Basics
54/69
IKam'le
-
8/9/2019 Socket Programming Basics
55/69
@@
One thread 'er client Almost li*e using for*+ - ust call
'thread>create instead/
Using threads ma*es it easier +lessoverhead to have sibling 'rocesses
share information/
;haring information must be donecarefully +use 'thread>muteK
-
8/9/2019 Socket Programming Basics
56/69
@'
Preor/()Hd ;erver Creating a new 'rocess for each client
is eK'ensive/
&e can create a bunch of 'rocesses,each of which can ta*e care of a client/
Iach child 'rocess is an iterative
server/
-
8/9/2019 Socket Programming Basics
57/69
@M
Preor/()Hd )CP ;erver .nitial 'rocess creates soc*et and binds
to well *nown address/
Process now calls or/()a bunch oftimes/
All children call accet(). )he neKt incoming connection will be
handed to one child/
-
8/9/2019 Socket Programming Basics
58/69
@8
Prefor*ing :aving too many 'refor*ed children can
be bad/
Using dynamic 'rocess allocationinstead of a hard-coded number of
children can avoid 'roblems/
)he 'arent 'rocess ust manages thechildren, doesnHt worry about clients/
-
8/9/2019 Socket Programming Basics
59/69
@E
;oc*ets library vs/ system call
A 'refor*ed )CP server wonHt usually
wor* the way we want if socketsis not
'art of the *ernel% calling acce't+ is a library call, not an
atomic o'eration/
&e can get around this by ma*ing sureonly one child calls acce't+ at a time
using some loc*ing scheme/
-
8/9/2019 Socket Programming Basics
60/69
'6
Prethreaded ;erver
;ame benefits as 'refor*ing/
Can also have the main thread do all
the calls to acce't+ and hand off eachclient to an eKisting thread/
-
8/9/2019 Socket Programming Basics
61/69
'1
&hatHs the best server design
for my a''lication( 0any factors%
eK'ected number of simultaneous clients/
)ransaction si2e +time to com'ute orloo*u' the answer
ariability in transaction si2e/
Available system resources +'erha's whatresources can be re7uired in order to run
the service/
-
8/9/2019 Socket Programming Basics
62/69
'2
;tatelessness
tate' .nformation that a server
maintains about the status of ongoing
client interactions/ Connectionless servers that *ee' state
information must be designed carefully";close(listen_sd";e?it($";else)rintf(>Iser8er ind(" is 3:@n>";
-
8/9/2019 Socket Programming Basics
66/69
/* 4et the listen acklog */rc 9 listen(listen_sd, E";if(rc = 7"{)error(>Iser8er listen(" error>";
close(listen_sd";e?it($";else)rintf(>Iser8er listen(" is 3:@n>";
/* Inform the user that the ser8er is ready */)rintf(>!he Iser8er is ready@n>";
/* Go through the loo) once for each connection */
for(i97; i = num; iHH"{/* 5ait for an incoming connection */)rintf(>Iteration JKd@n>, iH$";)rintf(> 1aiting on acce)t("@n>";acce)t_sd 9 acce)t(listen_sd, NLMM, NLMM";if(acce)t_sd = 7"{)error(>Iser8er acce)t(" error>";
close(listen_sd";e?it($";else)rintf(>acce)t(" is 3: and com)leted successfully@n>";
-
8/9/2019 Socket Programming Basics
67/69
/* ecei8e a message from the client */)rintf(>I am 1aiting client(s" to send message(s" to me...@n>";rc 9 rec8(acce)t_sd, uffer, sieof(uffer", 7";if(rc =9 7"{)error(>Iser8er rec8(" error>";
close(listen_sd";close(acce)t_sd";e?it($";else)rintf(>!he message from client @>Ks@>@n>, uffer";/* cho the data ack to the client */)rintf(>choing it ack to client...@n>";len 9 rc;rc 9 send(acce)t_sd, uffer, len, 7";
if(rc =9 7"{)error(>Iser8er send(" error>";close(listen_sd";close(acce)t_sd";e?it($";else)rintf(>Iser8er send(" is 3:.@n>";/* 6lose the incoming connection */close(acce)t_sd";/* 6lose the listen socket */close(listen_sd";return 7;
Concurrent server +using for*
-
8/9/2019 Socket Programming Basics
68/69
Concurrent server +using for*
inet_ntoa=remoteaddr(sin_addr>nebu0 ''do any other tasks as needede3it=
KK
-
8/9/2019 Socket Programming Basics
69/69
!AN: C3L