SlideShare a Scribd company logo
SYSTEMS PROGRAMMING
LECTURE 8
NETWORK PROGRAMMING
SOCKETS
• BSD sockets provide a way how processes can inter-
communicate
• BSD sockets offer 4 communication protocols which
cannot normally be inter-connected: UNIX, Internet,
NS and ISO OSI. We will cover the first two
• Sockets are named end point IPC structures
• All sockets range over a particular protocol and are
of a certain type
• We will only consider types which provide connection-
oriented, reliable, sequenced and unduplicated flow
of data, known as stream sockets
INTERNET PRELIMINARIES
• Our discussion will only skim the surface of the vast
subject.
• Every computer on the internet has associated to it a
unique identifier which is used to pass data to and fro
• This identifier can be seen as the postal address of
each computer (host). Computers in between two end
points act as carriers on these messages
• Delivery of each message is the responsibility of thee
intermediate computers and no central forwarding
authority exists
• This addressing protocol is called the IP protocol
IP, DNS AND TCP/IP
• These identifiers are called IP addresses and are 32-
bit number (for IPv4)
• IP addresses are normally displayed as dot
separated values (ex: 193.188.34.119)
• 127.0.01 is special, and called to loopback
• For each message that goes through the internet, the
source and destination address must be specified
• A specific protocol exists which allow human readable
values to be translated into IP addresses. This is
called the Domain Name System (DNS)
IP, DNS AND TCP/IP
• A hierarchy exists giving shared responsibility to
resolve names to IP addresses for all names in the
world
• A typical name would be albert.grid.um.edu.mt,
which translates to the UoM cluster’s IP address
using DNS
• IP provides the way how to find a host to deliver
messages to, yet it does not guarantee reliable flow
of data
• On the network, errors occur and messages are
sometimes lost or corrupted
IP, DNS AND TCP/IP
• Also, the order messages arrive in is not guaranteed
• The Transmission Control Protocol (TCP) resides on
top of IP and guarantees data flow reliability and
flow control
• Also, it makes connection-oriented transmission
possible
• For a connection on a host (single IP address), there
exists many entry points through which there may be
many-to-many connections. These are called ports
IP, DNS AND TCP/IP
• Ports can only sustain many-to-one connections on
the server side and are numbered 1 – 65536
• Internet ports 1 – 1023 are considered reserved
and in fact can only be used by the superuser
• Ports from 1024 to 5000 can be used at will and
will also be assigned automatically by the system
• The command nestat tells you what connections
are open at any one time on the system
• When a connection is dropped on both ends, the
system cleans up any pending connections
TCP/IP SOCKETS
• Sockets are able to open a connection on a port
and transmit whatever data to and fro the
recipient
• To establish a connection through a port, the
following tuple must be totally defined in the
system: <protocol, local-addr, local-
port, foreign-addr, foreign-port>
• In a server-client setup, the server provides the
local attributes and then waits for a connection
from the client
TCP/IP SOCKETS
• A connection from the client provides all the
necessary data to fill this tuple
• The client initiates the connection to the remote
server, using a known remote IP address and
port number on which the server is listening
• This provides all the data for the local part of
the tuple
• On the whole internet, each of these tuples must
be unique
NETWORK BYTE ORDERING
• Some computer architectures are big endian and some
are little endian
• For example, Intel architectures are little endian
• To be able to communicate on the internet, a network
byte ordering has been defined
• Network byte ordering is big endian for 16 and 32 bit
integers
• When passing values to be used at the network layers,
we need to make the appropriate conversions
NETWORK BYTE ORDERING
• The following library functions handle the potential
byte order differences between different computer
architectures
• ‘h’ stands for host while ‘n’ stands for network values
#include <sys/types.h>
#include <netinet/in.h>
u_long htonl(u_long hostlong);
u_short htons(u_short hostshort);
u_long ntohl(u_long netlong);
u_short ntohs(u_short netshort);
BYTE OPERATIONS
• Whenever a series of bytes have to be copied, use
bcopy
• bcopy is better suited than strcpy since a series
of bytes might contain ‘/0’ inside it.
• When using network structures, be sure to apply
bzero before using them
#include <string.h>
void bcopy(char *src, char *dest, int nbytes);
void bzero(char *dest, int nbytes);
int bcmp(char *ptr1, char *ptr2, int nbytes);
ADDRESS CONVERSION
• Given an IP address stored inside a string,
inter_addr returns the address in network byte
order
• inet_ntoa performs the opposite operation
• Every subsequent call to inet_ntoa overwrites
the statically return string
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
unsigned long inet_addr(const char* ptr);
char *inet_ntoa(struct in_addr inaddr);
SOCKET ACCESS CONTROL - SERVER
• A server opens a specific port on the local IP
address and listens for a connection
• A client connects to this port and the connection is
established
• Any data coming on the opened port will be
forwarded to the server
• An internal kernel table is maintained to decide
which port and IP outgoing data has to go
SOCKET ACCESS CONTROL - CLIENT
• A client requests access to a specific port on the
local IP
• Access is granted if the port is not bound to another
process
• If successful, the client initiates a connection to a
well-known port and IP, on which the server is
listening
• Using again an internal table, incoming data will be
passed to the client bound to the port
• Outgoing data will be forwarded to the server port
SOCKET ACCESS
• When using sockets apply the following to your
programs:
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
• To compile programs using sockets on SunOS
systems use: gcc –lnsl –lsocket myprog.c
• Some programs such as ping, netstat and
traceroute are available in the directory
/usr/sbin
SOCKET ACCESS CONTROL - CLIENT
• All sockets of all protocols and type use struct
sockaddr as a base communication structure
• This structure is a general structure which is then
applied type-casted to the specific protocol or type
required
struct sockaddr
{
u_short sa_family; // AF_xxxx
char sa_data[14]; // protocol specific
}
SOCKET ACCESS CONTROL - CLIENT
• For internet access, struct sockaddr_in is used. It
is applied wherever struct sockaddr is required.
• Be sure to bzero() the structure before using it
struct sockaddr_in
{
short sin_family; // AF_INET
u_short sin_port; // 16-bi port no.
struct in_addr sin_addr; // 32-bit IP in NBO
char sin_zero[8]; // Set to 0
}
struct in_addr {
u_long s_addr; // 32-bit IP in NBO
}
INTERNET SOCKETS
• socket() opens a new socket and returns its
socket descriptor
• For internet access, family is set to AF_INET,
type to SOCK_STREAM and protocol to
0 (thus leaving the system to assign the best
protocol)
• The socket() function does not open any
connections or access any port but creates and
endpoint for communications
INTERNET SOCKETS
• Protocol 0 is internally changed to IPPROTO_TCP
when AF_INET and SOCK_STREAM are used
• We can set three kinds of socket options:
• Generic options that work with all socket types
• Options that are managed at socket level, but
depend on underlying protocols for support
• Protocol-specific options
int socket(int family, int type,
int protocol);
return socket descriptor or -1 on error
SOCKET OPTIONS
• The level argument identifies the protocol to which
the option applies (eg IPPROTO_TCP)
• If option is generic then SOL_SOCKET is used
• The val argument points to a data structure
int setsockopt(int sockfd, int level,
int option, const void *val,
socklen_t len);
int getsockopt(int sockfd, int level,
int option, void *restrict val,
socklen_t restrict lenp);
Return 0 if OK, 1 on error
SOME SOCKET OPTIONS
SO_ACCEPTCONN Return whether a socket is enabled for
listening
SO_DEBUG Debugging in network drivers
SO_DONTROUTE Bypass normal routing
SO_ERROR Return and clear pending socket errors
SO_KEEPALIVE Periodic keep-alive messages
SO_RCVBUF Size of the receive buffer
SO_RCVTIMEO Timeout value for a socket receive call
SO_REUSEADDR Reuse address in bind
SO_SENDBUF Size of the send buffer
SO_SNDTIMEO Timeout value for a socket send call
BINDING SOCKETS
• A server binds a socket to the local IP address
and to a port number it wants to listen on
• A client can also bind a socket to the local IP
address and a port number, but usually we let
the system assign an unused port automatically
• bind() completes the local part of the socket
tuple
• addrlen should state the size of myaddr
BINDING SOCKETS
• After binding a socket, any messages received on
the bound port will be passed to the binding
process
• Not more than one server should bind itself to a
specific port
• Non-superusers can only bind port number 1024-
65536
int bind(int sockfd,
struct sockaddr *myaddr,
int addrlen);
Returns -1 on error
CONNECTING
• A client tries to connect to a foreign IP address and port
by putting the necessary entries in struct
sockaddr_in and then invoking connect()
• On success, the connection is established and data can
flow to and fro
• The connect() function completed the foreign part of
the socket tuple
• If a client calls connect() without first calling bind()
on the socket (unbound) then the system automatically
assigns the local IP address and a free unused port to the
specified socket. In this case, connect() also completes
the local part of the socket tuple
CONNECTING
• When trying to connect, the following errors might
be reported in errno:
ETIMEDOUT: timeout on trying to connect
ECONNREFUSED: server refused the connection
ENETDOWN or EHOSTDOWN: The communication
system was unable to connect
ENETUNREACH or EHOSTUNREACH: Network or
host unknown
EISCONN: Socket is already connected
EADDRINUSE: Address is already in use
CONNECTING
• addrlen should state the size of myaddr
• Internally a connection is retried several times
until timeout or success
int connect(int sockfd,
struct addr *serveraddr,
int addrlen);
Returns -1 on error
LISTENING
• After a server binds a specific socket to an IP address
and a port, it registers the socket to listen() for
connections
• The backlog specifies the number of requests for
connections that should be queued until the server can
handle them (normally 5, maximum allowed)
• If the backlog gets full, new connection requests are
simply ignored)
int listen(int sockfd,
int backlog);
Returns -1 on error
CONNECTION ACCEPTANCE
• After a server registers the socket to listen on a
connection, it tries to accept a connection
• accept() blocks until a connection request exists on
the queue of pending connections
• accept() completes the foreign part of the socket
tuple for the server
• All connection requests are accepted, so it is up to the
server to close a connection from an unwanted client
• accept() returns a new socket descriptor to access
the new connection
CONNECTING
• The original socket is left open to be able to accept
more connections
• accept fills the client structure with the details of the
connecting client
• addrlen is a pointer to an integer specifying the size
allocated to client and on return it will contain the true
size used for client
int accept(int sockfd,
struct addr *client,
int *addrlen);
Return new socket descriptor or
-1 on error
ITERATIVE AND CONCURRENT SERVERS
• There are two types of servers depending on their
behaviour after the accept call:
• Concurrent: After accept, a new child is
forked which closes the original socket and
handles the new connection using the new socket.
Meanwhile the parent closes the new socket and
calls accept again to wait for a new
connection
• Iterative: After accept, the server handles the
new connections, closes it and then call accept
again
CLOSING
• Calling close() will terminate the connection
• If there is any pending data on the socket, the
system will try to send it through
• Any process (client or server) trying to access, read
from or write to a broken stream will receive the
SIGPIPE signal
• The SIGPIPE signal normally terminates the program.
Handling this signal makes your program fault
tolerant to an abrupt loss of connection
int close(int sockfd);
Returns -1 on error
READING AND WRITING
• The usual read and write system call are used
to access sockets
• The only difference in the system call is that the
socket descriptor is used instead of the normal file
descriptor
• All writes on a socket will block until the data will
be sent through the other host, but not until that
process reads it
• All read from a socket will block until some data is
available. read will return the number of bytes
read, which may be less than requested
SERVER CLIENT TYPICAL DESIGN
The communication
protocol between
the server and
client is crucial in
that it provides
synchronisation,
overall data flow
reliability and
correctness
UNIX DOMAIN SOCKETS
• Use the same connection protocol as internet
sockets, yet are used to communicate on the same
system
• Another form of IPC limited to the same host
machine
• All data flow is reliable since data is redirected in
the kernel
• Instead of IP addresses and port, pathname of
files are used
• The file referenced is created in some system, yet
this is not necessary
UNIX DOMAIN SOCKETS
• One cannot open a socket file using the open
system call
• A socket file has type S_IFSOCK and can be
tested with the S_ISSOCK() macro in conjunction
with the fstat() system call
• struct sockaddr_un is used whenever
struct sockaddr is required
• All Unix domain sockets use the <sys/un.h>
header file
• sun_path is a null terminated string which is
used for the path to be used
UNIX DOMAIN SOCKETS
• To create a UNIX socket, the socket call is used with
family set to AF_UNIX, type to SOCK_STREAM
and protocol equal to 0
• The usual calls to bind, connect, listen and
accept are used to open stream connection using
struct sockaddr_un
struct sockaddr_un
{
short sun_family; // AF_UNIX
char sun_path[108]; // pathname
}
UNIX DOMAIN SOCKETS
• A connection is opened between two sockets, where
each socket is associated with a different
pathname
• On some systems, socket creation is allowed
depending on access rights to the pathname’s
directory
• Closing a UNIX socket will remove the file from the
system
• read, write and all other system calls we used
for internet sockets are valid for UNIX sockets

More Related Content

What's hot (20)

PDF
Chapter 2.1 : Data Stream
Ministry of Higher Education
 
PPT
Ports & sockets
myrajendra
 
PPT
IP Addressing
Kishore Kumar
 
PDF
Visual ip subnetting
SMC Networks Europe
 
PPTX
Socket programming or network programming
Mmanan91
 
PDF
Chapter 2 : Inet Address & Data Stream
Ministry of Higher Education
 
PPT
Types of ip address classes
greatbury
 
PPTX
Internet address
Shubham Dwivedi
 
PDF
Chap 1 Network Theory & Java Overview
Ministry of Higher Education
 
PPTX
Computer network coe351- part3-final
Taymoor Nazmy
 
PPTX
MAC & IP addresses
NetProtocol Xpert
 
PPT
Ip address and subnetting
IGZ Software house
 
PPTX
Ip addressing
Tanvir Amin
 
PPTX
Mac addresses(media access control)
Ismail Mukiibi
 
PDF
InfiniFlux IP Address Type
InfiniFlux
 
PPTX
Socket programming in C#
Nang Luc Vu
 
PPT
02 protocols and tcp-ip
myl_1116
 
PPTX
Mac Filtering
Devang Doshi
 
PPTX
Dynamic NAT
NetProtocol Xpert
 
Chapter 2.1 : Data Stream
Ministry of Higher Education
 
Ports & sockets
myrajendra
 
IP Addressing
Kishore Kumar
 
Visual ip subnetting
SMC Networks Europe
 
Socket programming or network programming
Mmanan91
 
Chapter 2 : Inet Address & Data Stream
Ministry of Higher Education
 
Types of ip address classes
greatbury
 
Internet address
Shubham Dwivedi
 
Chap 1 Network Theory & Java Overview
Ministry of Higher Education
 
Computer network coe351- part3-final
Taymoor Nazmy
 
MAC & IP addresses
NetProtocol Xpert
 
Ip address and subnetting
IGZ Software house
 
Ip addressing
Tanvir Amin
 
Mac addresses(media access control)
Ismail Mukiibi
 
InfiniFlux IP Address Type
InfiniFlux
 
Socket programming in C#
Nang Luc Vu
 
02 protocols and tcp-ip
myl_1116
 
Mac Filtering
Devang Doshi
 
Dynamic NAT
NetProtocol Xpert
 

Viewers also liked (14)

PDF
Fundamentals of Transport Phenomena ChE 715
HelpWithAssignment.com
 
PDF
Manufacturing Process Selection and Design
HelpWithAssignment.com
 
PDF
Cash Dividend Assignment Help
HelpWithAssignment.com
 
PDF
Ruby Programming Assignment Help
HelpWithAssignment.com
 
PDF
Fundamentals of Transport Phenomena ChE 715
HelpWithAssignment.com
 
PDF
System Programming - Interprocess communication
HelpWithAssignment.com
 
PDF
Get 24/7 Reliable Engineering Assignment Help, 100% error free, money back g...
HelpWithAssignment.com
 
PDF
System Programming Assignment Help- Signals
HelpWithAssignment.com
 
PPT
Factorial Experiments
HelpWithAssignment.com
 
PPTX
Game theory Bayesian Games at HelpWithAssignment.com
HelpWithAssignment.com
 
PPTX
Tips for writing a good biography
HelpWithAssignment.com
 
PPTX
Customer relationship management
HelpWithAssignment.com
 
Fundamentals of Transport Phenomena ChE 715
HelpWithAssignment.com
 
Manufacturing Process Selection and Design
HelpWithAssignment.com
 
Cash Dividend Assignment Help
HelpWithAssignment.com
 
Ruby Programming Assignment Help
HelpWithAssignment.com
 
Fundamentals of Transport Phenomena ChE 715
HelpWithAssignment.com
 
System Programming - Interprocess communication
HelpWithAssignment.com
 
Get 24/7 Reliable Engineering Assignment Help, 100% error free, money back g...
HelpWithAssignment.com
 
System Programming Assignment Help- Signals
HelpWithAssignment.com
 
Factorial Experiments
HelpWithAssignment.com
 
Game theory Bayesian Games at HelpWithAssignment.com
HelpWithAssignment.com
 
Tips for writing a good biography
HelpWithAssignment.com
 
Customer relationship management
HelpWithAssignment.com
 
Ad

Similar to Network Programming Assignment Help (20)

PDF
lab04.pdf
SaidiCalala
 
PDF
Sockets
Indrasena Reddy
 
PPT
Sockets
Gopaiah Sanaka
 
PPT
sockets_intro.ppt
AnilGupta681764
 
PPT
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
senthilnathans25
 
PPT
Basic socket programming
Kristian Arjianto
 
PPT
Sockets intro
AviNash ChaVhan
 
PPT
Introduction to sockets tcp ip protocol.ppt
MajedAboubennah
 
PDF
sockets
AbhinavRapartiwar
 
PPTX
L5-Sockets.pptx
ycelgemici1
 
PPTX
Basics of sockets
AviNash ChaVhan
 
PDF
socketProgramming-TCP-and UDP-overview.pdf
Shilpachaudhari10
 
PPT
Np unit2
vamsitricks
 
PPTX
Socket programming
Anurag Tomar
 
PPT
03-socketprogramming for college students.ppt
SoumabhaRoy
 
PPT
03-socketprogrsamming forcoleeger students.ppt
SoumabhaRoy
 
PPT
Sockets in unix
swtjerin4u
 
PPT
lecture03 on socket programming000000.ppt
SoumabhaRoy
 
PPT
lecture03for socket programming college.ppt
SoumabhaRoy
 
PDF
network programming lab manuaal in this file
shivani158351
 
lab04.pdf
SaidiCalala
 
Sockets
Gopaiah Sanaka
 
sockets_intro.ppt
AnilGupta681764
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
senthilnathans25
 
Basic socket programming
Kristian Arjianto
 
Sockets intro
AviNash ChaVhan
 
Introduction to sockets tcp ip protocol.ppt
MajedAboubennah
 
L5-Sockets.pptx
ycelgemici1
 
Basics of sockets
AviNash ChaVhan
 
socketProgramming-TCP-and UDP-overview.pdf
Shilpachaudhari10
 
Np unit2
vamsitricks
 
Socket programming
Anurag Tomar
 
03-socketprogramming for college students.ppt
SoumabhaRoy
 
03-socketprogrsamming forcoleeger students.ppt
SoumabhaRoy
 
Sockets in unix
swtjerin4u
 
lecture03 on socket programming000000.ppt
SoumabhaRoy
 
lecture03for socket programming college.ppt
SoumabhaRoy
 
network programming lab manuaal in this file
shivani158351
 
Ad

Recently uploaded (20)

PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 

Network Programming Assignment Help

  • 2. SOCKETS • BSD sockets provide a way how processes can inter- communicate • BSD sockets offer 4 communication protocols which cannot normally be inter-connected: UNIX, Internet, NS and ISO OSI. We will cover the first two • Sockets are named end point IPC structures • All sockets range over a particular protocol and are of a certain type • We will only consider types which provide connection- oriented, reliable, sequenced and unduplicated flow of data, known as stream sockets
  • 3. INTERNET PRELIMINARIES • Our discussion will only skim the surface of the vast subject. • Every computer on the internet has associated to it a unique identifier which is used to pass data to and fro • This identifier can be seen as the postal address of each computer (host). Computers in between two end points act as carriers on these messages • Delivery of each message is the responsibility of thee intermediate computers and no central forwarding authority exists • This addressing protocol is called the IP protocol
  • 4. IP, DNS AND TCP/IP • These identifiers are called IP addresses and are 32- bit number (for IPv4) • IP addresses are normally displayed as dot separated values (ex: 193.188.34.119) • 127.0.01 is special, and called to loopback • For each message that goes through the internet, the source and destination address must be specified • A specific protocol exists which allow human readable values to be translated into IP addresses. This is called the Domain Name System (DNS)
  • 5. IP, DNS AND TCP/IP • A hierarchy exists giving shared responsibility to resolve names to IP addresses for all names in the world • A typical name would be albert.grid.um.edu.mt, which translates to the UoM cluster’s IP address using DNS • IP provides the way how to find a host to deliver messages to, yet it does not guarantee reliable flow of data • On the network, errors occur and messages are sometimes lost or corrupted
  • 6. IP, DNS AND TCP/IP • Also, the order messages arrive in is not guaranteed • The Transmission Control Protocol (TCP) resides on top of IP and guarantees data flow reliability and flow control • Also, it makes connection-oriented transmission possible • For a connection on a host (single IP address), there exists many entry points through which there may be many-to-many connections. These are called ports
  • 7. IP, DNS AND TCP/IP • Ports can only sustain many-to-one connections on the server side and are numbered 1 – 65536 • Internet ports 1 – 1023 are considered reserved and in fact can only be used by the superuser • Ports from 1024 to 5000 can be used at will and will also be assigned automatically by the system • The command nestat tells you what connections are open at any one time on the system • When a connection is dropped on both ends, the system cleans up any pending connections
  • 8. TCP/IP SOCKETS • Sockets are able to open a connection on a port and transmit whatever data to and fro the recipient • To establish a connection through a port, the following tuple must be totally defined in the system: <protocol, local-addr, local- port, foreign-addr, foreign-port> • In a server-client setup, the server provides the local attributes and then waits for a connection from the client
  • 9. TCP/IP SOCKETS • A connection from the client provides all the necessary data to fill this tuple • The client initiates the connection to the remote server, using a known remote IP address and port number on which the server is listening • This provides all the data for the local part of the tuple • On the whole internet, each of these tuples must be unique
  • 10. NETWORK BYTE ORDERING • Some computer architectures are big endian and some are little endian • For example, Intel architectures are little endian • To be able to communicate on the internet, a network byte ordering has been defined • Network byte ordering is big endian for 16 and 32 bit integers • When passing values to be used at the network layers, we need to make the appropriate conversions
  • 11. NETWORK BYTE ORDERING • The following library functions handle the potential byte order differences between different computer architectures • ‘h’ stands for host while ‘n’ stands for network values #include <sys/types.h> #include <netinet/in.h> u_long htonl(u_long hostlong); u_short htons(u_short hostshort); u_long ntohl(u_long netlong); u_short ntohs(u_short netshort);
  • 12. BYTE OPERATIONS • Whenever a series of bytes have to be copied, use bcopy • bcopy is better suited than strcpy since a series of bytes might contain ‘/0’ inside it. • When using network structures, be sure to apply bzero before using them #include <string.h> void bcopy(char *src, char *dest, int nbytes); void bzero(char *dest, int nbytes); int bcmp(char *ptr1, char *ptr2, int nbytes);
  • 13. ADDRESS CONVERSION • Given an IP address stored inside a string, inter_addr returns the address in network byte order • inet_ntoa performs the opposite operation • Every subsequent call to inet_ntoa overwrites the statically return string #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> unsigned long inet_addr(const char* ptr); char *inet_ntoa(struct in_addr inaddr);
  • 14. SOCKET ACCESS CONTROL - SERVER • A server opens a specific port on the local IP address and listens for a connection • A client connects to this port and the connection is established • Any data coming on the opened port will be forwarded to the server • An internal kernel table is maintained to decide which port and IP outgoing data has to go
  • 15. SOCKET ACCESS CONTROL - CLIENT • A client requests access to a specific port on the local IP • Access is granted if the port is not bound to another process • If successful, the client initiates a connection to a well-known port and IP, on which the server is listening • Using again an internal table, incoming data will be passed to the client bound to the port • Outgoing data will be forwarded to the server port
  • 16. SOCKET ACCESS • When using sockets apply the following to your programs: #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> • To compile programs using sockets on SunOS systems use: gcc –lnsl –lsocket myprog.c • Some programs such as ping, netstat and traceroute are available in the directory /usr/sbin
  • 17. SOCKET ACCESS CONTROL - CLIENT • All sockets of all protocols and type use struct sockaddr as a base communication structure • This structure is a general structure which is then applied type-casted to the specific protocol or type required struct sockaddr { u_short sa_family; // AF_xxxx char sa_data[14]; // protocol specific }
  • 18. SOCKET ACCESS CONTROL - CLIENT • For internet access, struct sockaddr_in is used. It is applied wherever struct sockaddr is required. • Be sure to bzero() the structure before using it struct sockaddr_in { short sin_family; // AF_INET u_short sin_port; // 16-bi port no. struct in_addr sin_addr; // 32-bit IP in NBO char sin_zero[8]; // Set to 0 } struct in_addr { u_long s_addr; // 32-bit IP in NBO }
  • 19. INTERNET SOCKETS • socket() opens a new socket and returns its socket descriptor • For internet access, family is set to AF_INET, type to SOCK_STREAM and protocol to 0 (thus leaving the system to assign the best protocol) • The socket() function does not open any connections or access any port but creates and endpoint for communications
  • 20. INTERNET SOCKETS • Protocol 0 is internally changed to IPPROTO_TCP when AF_INET and SOCK_STREAM are used • We can set three kinds of socket options: • Generic options that work with all socket types • Options that are managed at socket level, but depend on underlying protocols for support • Protocol-specific options int socket(int family, int type, int protocol); return socket descriptor or -1 on error
  • 21. SOCKET OPTIONS • The level argument identifies the protocol to which the option applies (eg IPPROTO_TCP) • If option is generic then SOL_SOCKET is used • The val argument points to a data structure int setsockopt(int sockfd, int level, int option, const void *val, socklen_t len); int getsockopt(int sockfd, int level, int option, void *restrict val, socklen_t restrict lenp); Return 0 if OK, 1 on error
  • 22. SOME SOCKET OPTIONS SO_ACCEPTCONN Return whether a socket is enabled for listening SO_DEBUG Debugging in network drivers SO_DONTROUTE Bypass normal routing SO_ERROR Return and clear pending socket errors SO_KEEPALIVE Periodic keep-alive messages SO_RCVBUF Size of the receive buffer SO_RCVTIMEO Timeout value for a socket receive call SO_REUSEADDR Reuse address in bind SO_SENDBUF Size of the send buffer SO_SNDTIMEO Timeout value for a socket send call
  • 23. BINDING SOCKETS • A server binds a socket to the local IP address and to a port number it wants to listen on • A client can also bind a socket to the local IP address and a port number, but usually we let the system assign an unused port automatically • bind() completes the local part of the socket tuple • addrlen should state the size of myaddr
  • 24. BINDING SOCKETS • After binding a socket, any messages received on the bound port will be passed to the binding process • Not more than one server should bind itself to a specific port • Non-superusers can only bind port number 1024- 65536 int bind(int sockfd, struct sockaddr *myaddr, int addrlen); Returns -1 on error
  • 25. CONNECTING • A client tries to connect to a foreign IP address and port by putting the necessary entries in struct sockaddr_in and then invoking connect() • On success, the connection is established and data can flow to and fro • The connect() function completed the foreign part of the socket tuple • If a client calls connect() without first calling bind() on the socket (unbound) then the system automatically assigns the local IP address and a free unused port to the specified socket. In this case, connect() also completes the local part of the socket tuple
  • 26. CONNECTING • When trying to connect, the following errors might be reported in errno: ETIMEDOUT: timeout on trying to connect ECONNREFUSED: server refused the connection ENETDOWN or EHOSTDOWN: The communication system was unable to connect ENETUNREACH or EHOSTUNREACH: Network or host unknown EISCONN: Socket is already connected EADDRINUSE: Address is already in use
  • 27. CONNECTING • addrlen should state the size of myaddr • Internally a connection is retried several times until timeout or success int connect(int sockfd, struct addr *serveraddr, int addrlen); Returns -1 on error
  • 28. LISTENING • After a server binds a specific socket to an IP address and a port, it registers the socket to listen() for connections • The backlog specifies the number of requests for connections that should be queued until the server can handle them (normally 5, maximum allowed) • If the backlog gets full, new connection requests are simply ignored) int listen(int sockfd, int backlog); Returns -1 on error
  • 29. CONNECTION ACCEPTANCE • After a server registers the socket to listen on a connection, it tries to accept a connection • accept() blocks until a connection request exists on the queue of pending connections • accept() completes the foreign part of the socket tuple for the server • All connection requests are accepted, so it is up to the server to close a connection from an unwanted client • accept() returns a new socket descriptor to access the new connection
  • 30. CONNECTING • The original socket is left open to be able to accept more connections • accept fills the client structure with the details of the connecting client • addrlen is a pointer to an integer specifying the size allocated to client and on return it will contain the true size used for client int accept(int sockfd, struct addr *client, int *addrlen); Return new socket descriptor or -1 on error
  • 31. ITERATIVE AND CONCURRENT SERVERS • There are two types of servers depending on their behaviour after the accept call: • Concurrent: After accept, a new child is forked which closes the original socket and handles the new connection using the new socket. Meanwhile the parent closes the new socket and calls accept again to wait for a new connection • Iterative: After accept, the server handles the new connections, closes it and then call accept again
  • 32. CLOSING • Calling close() will terminate the connection • If there is any pending data on the socket, the system will try to send it through • Any process (client or server) trying to access, read from or write to a broken stream will receive the SIGPIPE signal • The SIGPIPE signal normally terminates the program. Handling this signal makes your program fault tolerant to an abrupt loss of connection int close(int sockfd); Returns -1 on error
  • 33. READING AND WRITING • The usual read and write system call are used to access sockets • The only difference in the system call is that the socket descriptor is used instead of the normal file descriptor • All writes on a socket will block until the data will be sent through the other host, but not until that process reads it • All read from a socket will block until some data is available. read will return the number of bytes read, which may be less than requested
  • 34. SERVER CLIENT TYPICAL DESIGN The communication protocol between the server and client is crucial in that it provides synchronisation, overall data flow reliability and correctness
  • 35. UNIX DOMAIN SOCKETS • Use the same connection protocol as internet sockets, yet are used to communicate on the same system • Another form of IPC limited to the same host machine • All data flow is reliable since data is redirected in the kernel • Instead of IP addresses and port, pathname of files are used • The file referenced is created in some system, yet this is not necessary
  • 36. UNIX DOMAIN SOCKETS • One cannot open a socket file using the open system call • A socket file has type S_IFSOCK and can be tested with the S_ISSOCK() macro in conjunction with the fstat() system call • struct sockaddr_un is used whenever struct sockaddr is required • All Unix domain sockets use the <sys/un.h> header file • sun_path is a null terminated string which is used for the path to be used
  • 37. UNIX DOMAIN SOCKETS • To create a UNIX socket, the socket call is used with family set to AF_UNIX, type to SOCK_STREAM and protocol equal to 0 • The usual calls to bind, connect, listen and accept are used to open stream connection using struct sockaddr_un struct sockaddr_un { short sun_family; // AF_UNIX char sun_path[108]; // pathname }
  • 38. UNIX DOMAIN SOCKETS • A connection is opened between two sockets, where each socket is associated with a different pathname • On some systems, socket creation is allowed depending on access rights to the pathname’s directory • Closing a UNIX socket will remove the file from the system • read, write and all other system calls we used for internet sockets are valid for UNIX sockets