Stuck with your Network Programming Assignment Help. Get 24/7 help from tutors with Phd in the subject. Email us at support@helpwithassignment.com
Reach us at http://www.HelpWithAssignment.com
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