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
Ad

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
Ministry of Higher Education
 
Ports & sockets
Ports  & sockets Ports  & sockets
Ports & sockets
myrajendra
 
IP Addressing
IP AddressingIP Addressing
IP Addressing
Kishore Kumar
 
Visual ip subnetting
Visual ip subnettingVisual ip subnetting
Visual ip subnetting
SMC Networks Europe
 
Socket programming or network programming
Socket programming or network programmingSocket programming or network programming
Socket programming or network programming
Mmanan91
 
Chapter 2 : Inet Address & Data Stream
Chapter 2 : Inet Address & Data StreamChapter 2 : Inet Address & Data Stream
Chapter 2 : Inet Address & Data Stream
Ministry of Higher Education
 
Types of ip address classes
Types of ip address classesTypes of ip address classes
Types of ip address classes
greatbury
 
Internet address
Internet addressInternet address
Internet address
Shubham Dwivedi
 
Chap 1 Network Theory & Java Overview
Chap 1   Network Theory & Java OverviewChap 1   Network Theory & Java Overview
Chap 1 Network Theory & Java Overview
Ministry of Higher Education
 
Reserved ip addresses
Reserved ip addressesReserved ip addresses
Reserved ip addresses
Faculty of Computer Science Nangarhar University
 
Computer network coe351- part3-final
Computer network coe351- part3-finalComputer network coe351- part3-final
Computer network coe351- part3-final
Taymoor Nazmy
 
MAC & IP addresses
MAC & IP addressesMAC & IP addresses
MAC & IP addresses
NetProtocol Xpert
 
Ip address and subnetting
Ip address and subnettingIp address and subnetting
Ip address and subnetting
IGZ Software house
 
Ip addressing
Ip addressingIp addressing
Ip addressing
Tanvir Amin
 
Mac addresses(media access control)
Mac addresses(media access control)Mac addresses(media access control)
Mac addresses(media access control)
Ismail Mukiibi
 
InfiniFlux IP Address Type
InfiniFlux IP Address TypeInfiniFlux IP Address Type
InfiniFlux IP Address Type
InfiniFlux
 
Socket programming in C#
Socket programming in C#Socket programming in C#
Socket programming in C#
Nang Luc Vu
 
02 protocols and tcp-ip
02 protocols and tcp-ip02 protocols and tcp-ip
02 protocols and tcp-ip
myl_1116
 
Mac Filtering
Mac FilteringMac Filtering
Mac Filtering
Devang Doshi
 
Dynamic NAT
Dynamic NATDynamic NAT
Dynamic NAT
NetProtocol Xpert
 

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
HelpWithAssignment.com
 
Manufacturing Process Selection and Design
Manufacturing Process Selection and DesignManufacturing Process Selection and Design
Manufacturing Process Selection and Design
HelpWithAssignment.com
 
Scoping
ScopingScoping
Scoping
HelpWithAssignment.com
 
Cash Dividend Assignment Help
Cash Dividend Assignment Help Cash Dividend Assignment Help
Cash Dividend Assignment Help
HelpWithAssignment.com
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
HelpWithAssignment.com
 
Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715
HelpWithAssignment.com
 
System Programming - Interprocess communication
System Programming - Interprocess communicationSystem Programming - Interprocess communication
System Programming - Interprocess communication
HelpWithAssignment.com
 
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...
HelpWithAssignment.com
 
System Programming Assignment Help- Signals
System Programming Assignment Help- SignalsSystem Programming Assignment Help- Signals
System Programming Assignment Help- Signals
HelpWithAssignment.com
 
Factorial Experiments
Factorial ExperimentsFactorial Experiments
Factorial Experiments
HelpWithAssignment.com
 
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
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
HelpWithAssignment.com
 
Scope
ScopeScope
Scope
HelpWithAssignment.com
 
Customer relationship management
Customer relationship managementCustomer relationship management
Customer relationship management
HelpWithAssignment.com
 
Ad

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
KushalSrivastava23
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptx
RockyBhai46825
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
Ajit Nayak
 
+ Network Programming.pdf
+ Network Programming.pdf+ Network Programming.pdf
+ Network Programming.pdf
OluwafolakeOjo
 
chapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhjchapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhj
AmitDeshai
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
CEC Landran
 
ADDRESSING PADA TCP IP
ADDRESSING PADA TCP IPADDRESSING PADA TCP IP
ADDRESSING PADA TCP IP
Jennifer Daniel
 
Лекц 7
Лекц 7Лекц 7
Лекц 7
Muuluu
 
Tcp ip
Tcp ipTcp ip
Tcp ip
Dheeraj Sadawarte
 
Know the advantages and disadvantages of peer-to-peer network and a server-ba...
Know the advantages and disadvantages of peer-to-peer network and a server-ba...Know the advantages and disadvantages of peer-to-peer network and a server-ba...
Know the advantages and disadvantages of peer-to-peer network and a server-ba...
ekwinsi
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
Rakesh Madugula
 
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
Tanzila Kehkashan
 
Lecture set 7
Lecture set 7Lecture set 7
Lecture set 7
Gopi Saiteja
 
SOHO Network Setup Tutorial
SOHO Network Setup Tutorial SOHO Network Setup Tutorial
SOHO Network Setup Tutorial
junaidahmedsaba
 
Networking in python by Rj
Networking in python by RjNetworking in python by Rj
Networking in python by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Java socket programming
Java socket programmingJava socket programming
Java socket programming
Mohammed Abdalla Youssif
 
Week 2 - Computer networks lab - ACU.pptx
Week 2 - Computer networks lab - ACU.pptxWeek 2 - Computer networks lab - ACU.pptx
Week 2 - Computer networks lab - ACU.pptx
NourhanTarek23
 
Computer Networks basics
Computer Networks basicsComputer Networks basics
Computer Networks basics
BiplabaSamantaray
 
network-security_for cybersecurity_experts
network-security_for cybersecurity_expertsnetwork-security_for cybersecurity_experts
network-security_for cybersecurity_experts
abacusgtuc
 
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
 
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
KushalSrivastava23
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptx
RockyBhai46825
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
Ajit Nayak
 
+ Network Programming.pdf
+ Network Programming.pdf+ Network Programming.pdf
+ Network Programming.pdf
OluwafolakeOjo
 
chapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhjchapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhj
AmitDeshai
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
CEC Landran
 
Лекц 7
Лекц 7Лекц 7
Лекц 7
Muuluu
 
Know the advantages and disadvantages of peer-to-peer network and a server-ba...
Know the advantages and disadvantages of peer-to-peer network and a server-ba...Know the advantages and disadvantages of peer-to-peer network and a server-ba...
Know the advantages and disadvantages of peer-to-peer network and a server-ba...
ekwinsi
 
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
Tanzila Kehkashan
 
SOHO Network Setup Tutorial
SOHO Network Setup Tutorial SOHO Network Setup Tutorial
SOHO Network Setup Tutorial
junaidahmedsaba
 
Week 2 - Computer networks lab - ACU.pptx
Week 2 - Computer networks lab - ACU.pptxWeek 2 - Computer networks lab - ACU.pptx
Week 2 - Computer networks lab - ACU.pptx
NourhanTarek23
 
network-security_for cybersecurity_experts
network-security_for cybersecurity_expertsnetwork-security_for cybersecurity_experts
network-security_for cybersecurity_experts
abacusgtuc
 
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
 
Ad

Recently uploaded (20)

Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Grade 3 - English - Printable Worksheet (PDF Format)
Grade 3 - English - Printable Worksheet  (PDF Format)Grade 3 - English - Printable Worksheet  (PDF Format)
Grade 3 - English - Printable Worksheet (PDF Format)
Sritoma Majumder
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdfIntroduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
james5028
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Grade 3 - English - Printable Worksheet (PDF Format)
Grade 3 - English - Printable Worksheet  (PDF Format)Grade 3 - English - Printable Worksheet  (PDF Format)
Grade 3 - English - Printable Worksheet (PDF Format)
Sritoma Majumder
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdfIntroduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
james5028
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 

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