SlideShare a Scribd company logo
1 of 38
Download to read offline
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)

Chapter 2.1 : Data Stream
Chapter 2.1 : Data StreamChapter 2.1 : Data Stream
Chapter 2.1 : Data Stream
 
Ports & sockets
Ports  & sockets Ports  & sockets
Ports & sockets
 
IP Addressing
IP AddressingIP Addressing
IP Addressing
 
Visual ip subnetting
Visual ip subnettingVisual ip subnetting
Visual ip subnetting
 
Socket programming or network programming
Socket programming or network programmingSocket programming or network programming
Socket programming or network programming
 
Chapter 2 : Inet Address & Data Stream
Chapter 2 : Inet Address & Data StreamChapter 2 : Inet Address & Data Stream
Chapter 2 : Inet Address & Data Stream
 
Types of ip address classes
Types of ip address classesTypes of ip address classes
Types of ip address classes
 
Internet address
Internet addressInternet address
Internet address
 
Chap 1 Network Theory & Java Overview
Chap 1   Network Theory & Java OverviewChap 1   Network Theory & Java Overview
Chap 1 Network Theory & Java Overview
 
Reserved ip addresses
Reserved ip addressesReserved ip addresses
Reserved ip addresses
 
Computer network coe351- part3-final
Computer network coe351- part3-finalComputer network coe351- part3-final
Computer network coe351- part3-final
 
MAC & IP addresses
MAC & IP addressesMAC & IP addresses
MAC & IP addresses
 
Ip address and subnetting
Ip address and subnettingIp address and subnetting
Ip address and subnetting
 
Ip addressing
Ip addressingIp addressing
Ip addressing
 
Mac addresses(media access control)
Mac addresses(media access control)Mac addresses(media access control)
Mac addresses(media access control)
 
InfiniFlux IP Address Type
InfiniFlux IP Address TypeInfiniFlux IP Address Type
InfiniFlux IP Address Type
 
Socket programming in C#
Socket programming in C#Socket programming in C#
Socket programming in C#
 
02 protocols and tcp-ip
02 protocols and tcp-ip02 protocols and tcp-ip
02 protocols and tcp-ip
 
Mac Filtering
Mac FilteringMac Filtering
Mac Filtering
 
Dynamic NAT
Dynamic NATDynamic NAT
Dynamic NAT
 

Viewers also liked

Viewers also liked (14)

Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715
 
Manufacturing Process Selection and Design
Manufacturing Process Selection and DesignManufacturing Process Selection and Design
Manufacturing Process Selection and Design
 
Scoping
ScopingScoping
Scoping
 
Cash Dividend Assignment Help
Cash Dividend Assignment Help Cash Dividend Assignment Help
Cash Dividend Assignment Help
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715
 
System Programming - Interprocess communication
System Programming - Interprocess communicationSystem Programming - Interprocess communication
System Programming - Interprocess communication
 
Get 24/7 Reliable Engineering Assignment Help, 100% error free, money back g...
Get 24/7 Reliable Engineering  Assignment Help, 100% error free, money back g...Get 24/7 Reliable Engineering  Assignment Help, 100% error free, money back g...
Get 24/7 Reliable Engineering Assignment Help, 100% error free, money back g...
 
System Programming Assignment Help- Signals
System Programming Assignment Help- SignalsSystem Programming Assignment Help- Signals
System Programming Assignment Help- Signals
 
Factorial Experiments
Factorial ExperimentsFactorial Experiments
Factorial Experiments
 
Game theory Bayesian Games at HelpWithAssignment.com
Game theory Bayesian Games at HelpWithAssignment.comGame theory Bayesian Games at HelpWithAssignment.com
Game theory Bayesian Games at HelpWithAssignment.com
 
Tips for writing a good biography
Tips for writing a good biographyTips for writing a good biography
Tips for writing a good biography
 
Scope
ScopeScope
Scope
 
Customer relationship management
Customer relationship managementCustomer relationship management
Customer relationship management
 

Similar to Network Programming Assignment Help

09 Systems Software Programming-Network Programming.pptx
09 Systems Software Programming-Network Programming.pptx09 Systems Software Programming-Network Programming.pptx
09 Systems Software Programming-Network Programming.pptxKushalSrivastava23
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxRockyBhai46825
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using CAjit Nayak
 
+ Network Programming.pdf
+ Network Programming.pdf+ Network Programming.pdf
+ Network Programming.pdfOluwafolakeOjo
 
chapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhjchapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhjAmitDeshai
 
Socket Programming
Socket ProgrammingSocket Programming
Socket ProgrammingCEC Landran
 
Лекц 7
Лекц 7Лекц 7
Лекц 7Muuluu
 
OOP Lecture 24-Network Programming-Part1.pptx
OOP Lecture 24-Network Programming-Part1.pptxOOP Lecture 24-Network Programming-Part1.pptx
OOP Lecture 24-Network Programming-Part1.pptxTanzila Kehkashan
 
SOHO Network Setup Tutorial
SOHO Network Setup Tutorial SOHO Network Setup Tutorial
SOHO Network Setup Tutorial junaidahmedsaba
 
Course 102: Lecture 20: Networking In Linux (Basic Concepts)
Course 102: Lecture 20: Networking In Linux (Basic Concepts) Course 102: Lecture 20: Networking In Linux (Basic Concepts)
Course 102: Lecture 20: Networking In Linux (Basic Concepts) Ahmed El-Arabawy
 
Routing of netwok protocls and how .pptx
Routing of netwok protocls and how .pptxRouting of netwok protocls and how .pptx
Routing of netwok protocls and how .pptxsayidkhalif
 
Networking.pptx
Networking.pptxNetworking.pptx
Networking.pptxEsubesisay
 
Microcontroller.pptx
Microcontroller.pptxMicrocontroller.pptx
Microcontroller.pptxSaba651353
 

Similar to Network Programming Assignment Help (20)

09 Systems Software Programming-Network Programming.pptx
09 Systems Software Programming-Network Programming.pptx09 Systems Software Programming-Network Programming.pptx
09 Systems Software Programming-Network Programming.pptx
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptx
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
 
+ Network Programming.pdf
+ Network Programming.pdf+ Network Programming.pdf
+ Network Programming.pdf
 
chapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhjchapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhj
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
ADDRESSING PADA TCP IP
ADDRESSING PADA TCP IPADDRESSING PADA TCP IP
ADDRESSING PADA TCP IP
 
Лекц 7
Лекц 7Лекц 7
Лекц 7
 
Tcp ip
Tcp ipTcp ip
Tcp ip
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 
OOP Lecture 24-Network Programming-Part1.pptx
OOP Lecture 24-Network Programming-Part1.pptxOOP Lecture 24-Network Programming-Part1.pptx
OOP Lecture 24-Network Programming-Part1.pptx
 
Lecture set 7
Lecture set 7Lecture set 7
Lecture set 7
 
SOHO Network Setup Tutorial
SOHO Network Setup Tutorial SOHO Network Setup Tutorial
SOHO Network Setup Tutorial
 
Networking in python by Rj
Networking in python by RjNetworking in python by Rj
Networking in python by Rj
 
Java socket programming
Java socket programmingJava socket programming
Java socket programming
 
Computer Networks basics
Computer Networks basicsComputer Networks basics
Computer Networks basics
 
Course 102: Lecture 20: Networking In Linux (Basic Concepts)
Course 102: Lecture 20: Networking In Linux (Basic Concepts) Course 102: Lecture 20: Networking In Linux (Basic Concepts)
Course 102: Lecture 20: Networking In Linux (Basic Concepts)
 
Routing of netwok protocls and how .pptx
Routing of netwok protocls and how .pptxRouting of netwok protocls and how .pptx
Routing of netwok protocls and how .pptx
 
Networking.pptx
Networking.pptxNetworking.pptx
Networking.pptx
 
Microcontroller.pptx
Microcontroller.pptxMicrocontroller.pptx
Microcontroller.pptx
 

Recently uploaded

Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

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