akn cn 6 cs 8 socket programming
TRANSCRIPT
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
1/35
Computer networking/socket/naj/1
Network ProgrammingTCP/IP Socket Programming
BSD SocketsAjit K Nayak
Department of CSEA,
SILICON, Bhubaneswar
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
2/35
Computer networking/socket/naj/2
What is network program
Communicating among processes
The processes may reside
in a single computer or in computers connected to a network or
Computers across a network Client server computing
Request
Response
ServerClient
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
3/35
Computer networking/socket/naj/3
Examples ClientExamples Client--ServerServer
Web client Web server
(iexplorer, netscape
Navigator, mozzila, . . . ) (IIS, Apache) FTP Client FTP server
Telnet Client Telnet server . . .
These are all precompiled programs andmay be used to communicate across a
network.
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
4/35
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
5/35
Computer networking/socket/naj/5
Defining a Socket?
It is a two way, full duplex communication channel
An interface between application and the network
i.e.The application can send/receive data to/fromthe network via sockets
In UNIX terminology you can say that it is also a
file, Like file descriptor it is also recognized by asocket descriptor( a 16 bit integer)
Sockets are always created in pairs and they areused to communicate with other sockets
There are many kinds of sockets like Internet
sockets, UNIX sockets, . . .
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
6/35
Computer networking/socket/naj/6
SocketsSockets
The socket is the BSD method foraccomplishing interprocess communication
(IPC) in a network. Thats why also called BSD sockets.
There are two important types of internetsockets
Stream socket, -- Datagram socket
Other type of internet sockets are
Raw socket, -- Sequence packet
We will concentrate on stream and datagram soc.
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
7/35
Computer networking/socket/naj/7
Essential types of sockets
SOCK_DGRAM UDP
unreliable delivery
no order guarantees
no notion of connection
can send or receive
SOCK_STREAM
TCP
reliable delivery
in-order guaranteed
connection-oriented
bidirectional
App
socket3 2 1
Dest.
App
socket3 2 1 Dest
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
8/35
Computer networking/socket/naj/8
Stream Oriented Comm.Stream Oriented Comm.
Server Client
Socket
Write
bind
listen
Read
Connect
Write
Accept
Read ..
Create a Socket
Bind it to a local port
Listen for a incoming
connection request
Connect from a client
Accept the request
Talk to each other
Close the socket
Close Close.
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
9/35
Computer networking/socket/naj/9
How to ProgramHow to Program
We will use Socket API with C programmingin Linux environment
Socket API contains many data structures,functions and system calls which will help
us to write good and efficient network
programs
Requirement is any PC loaded with Linux, C
and Socket API
It is also possible to program in other
environments like windows and other UNIXsystems?
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
10/35
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
11/35
Computer networking/socket/naj/11
Byte ordersByte orders
Address A+1 Address A
Increasing memoryaddress
Address A Address A+1Increasing memory
address
MSB 16-bit value LSB
High-order byte Low-order byteLittle-endian byte order
High-order byte Low-order byteBig-endian byte order
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
12/35
Computer networking/socket/naj/12
Byte-ordering
Problem: different machines / OSs use different word
orderings
little-endian: lower bytes first
big-endian: higher bytes first
these machines may communicate with one anotherover the network
128.119.40.12
128 119 40 12
Big-Endianmachine 12.40.119.128
128 119 40 12
Little-Endianmachine
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
13/35
Computer networking/socket/naj/13
IPV4 Socket Add StructureIPV4 Socket Add Structure
struct sockaddr_in{
uint8_t sin_len;
sa_family_t sin_family;in_port_t sin_port;struct in_addr sin_addr;
char sin_zero[8];}; //datatypes are as ofposix.1gsin_len: length of structure?
included in 4.3 BSD-RenoSa_family_t: address family ofsocket address structure
k dd
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
14/35
Computer networking/socket/naj/14
IPV4 Socket Add StructureIPV4 Socket Add Structure
sin_family: socket address familyAF_INET IPv4 family
AF_INET6 IPv6AF_LOCAL UNIX domain
AF_ROUTE routing socket
AF_KEY key socket
in_port_t: 16 bit unsigned integer
sin_port: port no of TCP or UDP
This number is used to identify a particular
server program
P
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
15/35
Computer networking/socket/naj/15
Ports
Each host has 65,536ports
Some ports arereserved for specificapps called as IANAports or reserved ports,(0 1024) 20,21: FTP
23: Telnet
80: HTTP
1024 49151 arecalled IANA registeredports
Port 0
Port 1
Port 65535
Others are calledephemeral ports( IANA is
silent about it)A socket provides an
interface to address
IP:port pair
P 4 k ddIPV4 S k Add S
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
16/35
Computer networking/socket/naj/16
IPV4 Socket Add StructureIPV4 Socket Add Structure
The sin_zero member is unused, but it is setto zero ?
The length member was added in 4.3 BSD-Reno, when support for OSI was added
Length of structure 1+1+2+4+8 = 16 bytes
Socket address structures are used only on
a given host, the structure itself is not
communicated
But some fields like IP and port are used for
communication
C llS t C ll
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
17/35
Computer networking/socket/naj/17
System CallsSystem Calls
Creating a socket#include
int socket( int family, int type, int protocol); family specifies the protocol family
Family Description
AF_INET IPv4 protocols
AF_INET6 IPv6 protocols
AF_LOCALS Unix domain protocols
AF_ROUTE Routing sockets
AF_KEY Key socket
S C ll (2)S t C ll (2)
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
18/35
Computer networking/socket/naj/18
System Calls(2)System Calls(2)
type: communication typetype Description
SOCK_STREAM stream socketSOCK_DGRAM datagram socket
SOCK_RAW raw socket
protocol: specifies protocol, usually set to 0except for raw sockets (so that socket choose
correct protocol based on type) Note:
not all combination of socket family and type are valid.
S t C ll (3)S t C ll (3)
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
19/35
Computer networking/socket/naj/19
System Calls(3)System Calls(3)
YES are valid but do not have acronyms
There are also various other values for family andtype arguments
On success the socket function returns a non-
negative integer, called socket descriptor This call is used by both server and client
sockfd=socket(AF_INET, SOCK_STREAM,0);
AF_INET AF_LOCAL AF_LOCAL AF_ROUTE AF_KEY
SOCK_STREAM TCP TCP YES
SOCK_DGRAM UDP UDP YES
SOCK_RAW IPv4 IPv6 YES YES
S t C ll (4)S t C ll (4)
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
20/35
Computer networking/socket/naj/20
System Calls(4)System Calls(4)
#includeint bind(int sockfd, const struct sockaddr *myaddr,
socklen_t addrlen);
bind assigns a local protocol address to asocket
Local protocol address consists of IPaddress along with a port number
Second argument is a pointer(?) to addressstructure
Third argument is the length(size) of
address structure (32-bit integer)
S t C ll (5)S st C lls(5)
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
21/35
Computer networking/socket/naj/21
System Calls(5)System Calls(5)
With TCP, calling bind lets us specify a portnumber, an IP address, both or neither.
Process specifies Result
IP address Port
wildcard 0 Kernel chooses IP address andport
wildcard nonzero Kernel chooses IP address,
process specifies port
Local IP 0 Process specifies IP address,
Kernel chooses port
Local IP nonzero Process specifies IP address,and port
S t C ll (5)S st m C lls(5)
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
22/35
Computer networking/socket/naj/22
System Calls(5)System Calls(5)
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY)/* wild card */
serv_addr.sin_port=0;bind(sockfd, (struct sockaddr *)&serv_addr,
sizeof(serv_addr);
It returns 0 if OK or 1 on error
Normally a TCP client does not bind an IP
address to its socket. The Kernel choosesthe source IP when socket is connected,
based on outgoing interface.
B t d i f ti sByte ordering functions
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
23/35
Computer networking/socket/naj/23
Byte ordering functionsByte ordering functions
#include
uint32_t htonl(uint32_t hostlong); it converts the long
integerhostlong from host byte order to network byte
order.
uint16_t htons(uint16_t hostshort); it converts the short
integerhostshort from host byte order to network byte
order.
Both returns value in network byte order
uint32_t ntohl(uint32_t netlong); it converts the longintegernetlong from network byte order to host byte order.
uint16_t ntohs(uint16_t netshort); it converts the short
integernetshort from network byte order to host byte order. Both returns values in host byte order
System Calls(6)System Calls(6)
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
24/35
Computer networking/socket/naj/24
System Calls(6)System Calls(6)
#includeint listen(int sockfd, int backlog);
The listen function converts an unconnectedsocket into a passive socket, indicating thatthe kernel sould accept incoming connection
requests directed to this socket The call to listen moves the socket from the
CLOSED state to LISTEN state
The second argument specifies themaximum number of connection that the
kernel should queue for this socketlisten(sockfd,5);
System Calls(7)System Calls(7)
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
25/35
Computer networking/socket/naj/25
System Calls(7)System Calls(7)
#includeint connect(int sockfd, const struct sockaddr
*servaddr, socklen_t addrlen);
Used by a client to connect to a server.
The connect function initiates TCPs three-
way handshake(?). The function returns only when the
connection is established(0) or when anerror occurs(-1)
If the connect fails, the socket is no longer
usable and must be closed.
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
26/35
Errors with connectionErrors with connection
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
27/35
Computer networking/socket/naj/27
Errors with connectionErrors with connection
If client receives no response to its SYN segment,ETIMEDOUT is returned. (SYN is sent in every 6sec and another 24 sec) If no response is received
after a total of 75 secs, the error isreturned.(4.4BSD)
if server response is RST, it indicates no
process(port) is waiting for connection andECONNREFUSED is returned (hard error)
If clients SYN elicits an ICMP destination
unreachable from intermediate router, kernelsaves the message but keeps sending SYNs till 75sec. After which kernel returns EHOSTUNREACH
orENETUNEECH.(soft error)
System Calls(8)System Calls(8)
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
28/35
Computer networking/socket/naj/28
System Calls(8)System Calls(8)
#includeint accept(int sockfd, struct sockaddr *cliaddr,
socklen_t *addrlen);
It is called by TCP server to return the next completedconnection from the front of the connection queue.
If the completed connection queue is empty, the
process is put to sleep The cliaddr and addrlen arguments are used to return
the protocol address of the connected peer process.
The addrlen contains the sizeof client addressstructure and on return it contains the actual no ofbytes stored by the kernel in the socket address
structure
System Calls(8)System Calls(8)
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
29/35
Computer networking/socket/naj/29
System Calls(8)System Calls(8)
If accept is successful, it returns a new descriptorthat was automatically created by the kernel.
This new descriptor refers to the TCP connection
with the client Now first one is called the listening socket and the
second one is called the connected socket
A given server normally creates only one listeningsocket, which exists for the life time of the server.
The kernel creates one connected socket for eachclient connection that is accepted.
When server is finished serving a client,connected socket for that client is closed
System Calls(9)System Calls(9)
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
30/35
Computer networking/socket/naj/30
System Calls(9)System Calls(9)
addrlen = sizeof(cliaddr);connfd=accept(sockfd, (struct sockaddr *)
&cliaddr, &addrlen);
This function gives up to three values
An integer return, that is either a new socket
descriptor or an error indication(-1) The protocol address of the client process
(through cliaddr) and
Size of this address (through addrlen)
If protocol address is not required then both
cliaddr and addrlen is set to NULL;
System Calls(10)System Calls(10)
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
31/35
Computer networking/socket/naj/31
System Calls(10)System Calls(10)
#includeint close(int sockfd);
The default action is to mark the socket as closed
and return to process
The socket descriptor is no 0longer usable by the
process; It cannot be used as an argument to reador write
But TCP will try to send any data that is already
queued to be sent to other end, and after this thenormal TCP connection termination sequence
takes place.( 4-way handshaking?)
Network I/ONetwork I/O-- ReadingReading
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
32/35
Computer networking/socket/naj/32
Network I/ONetwork I/O- ReadingReading
Connection orientedint read(int sockfd, char *buf, int nbytes);
It reads nbytes(max) from socket to the buffer
Returns no of bytes read successfully from the socket
and 1 on error
Connection lessint recvfrom(int sockfd, char *buf, int nbytes, int flag,
struct sockaddr *from, int addrlen);
It receives nbytes(max) from a socket, whose address isgiven by the from address structure to the buffer
Returns no of bytes read successfully from the socket
and 1 on error
Network I/ONetwork I/O-- WritingWriting
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
33/35
Computer networking/socket/naj/33
Network I/ONetwork I/O WritingWriting
Connection orientedint write(int sockfd, char *buf, int nbytes);
It writes n bytes(max) to the socket from buffer
Returns no of bytes written successfully to the socket
and 1 on error
Connection lessint sendto(int sockfd, char *buf, int nbytes, int flag,
struct sockaddr *to, int addrlen);
It sends nbytes(max) to a socket, whose address isgiven by the to address structure from the buffer
Returns no of bytes sent successfully from the socket
and 1 on error
ReferencesReferences
-
8/9/2019 Akn CN 6 CS 8 Socket Programming
34/35
Computer networking/socket/naj/34
ReferencesReferences
W. Richard Stevens, UNIX network programming,vol 1, PE
Beejs Guide to Network Programming using
internet socketswww.ecst.csuchioco.edu/~beej/guide/net
Sockets Progrmming,
http://www.seit.wlv.ac.uk/~jphb/comm/sockets.html Introduction to network functions in C
http://shoe.bocks.com/net
Unix-socket-faq for network programmingftp://rtfm.mit.edu/pub/usenet/news.answers/unix-faq
http://www.ecst.csuchioco.edu/~beej/guide/nethttp://www.seit.wlv.ac.uk/~jphb/comm/sockets.htmlhttp://shoe.bocks.com/netftp://rtfm.mit.edu/pub/usenet/news.answers/unix-faqftp://rtfm.mit.edu/pub/usenet/news.answers/unix-faqhttp://shoe.bocks.com/nethttp://www.seit.wlv.ac.uk/~jphb/comm/sockets.htmlhttp://www.seit.wlv.ac.uk/~jphb/comm/sockets.htmlhttp://www.ecst.csuchioco.edu/~beej/guide/nethttp://www.ecst.csuchioco.edu/~beej/guide/net -
8/9/2019 Akn CN 6 CS 8 Socket Programming
35/35
Computer networking/socket/naj/35
Thank You?
Mail to [email protected]