You are on page 1of 35

Network Programming

TCP/IP Socket Programming


BSD Sockets
Ajit K Nayak
Department of CSEA,
SILICON, Bhubaneswar

Computer networking/socket/naj/1
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
Client Server
Response
Computer networking/socket/naj/2
Examples Client-Server
• Web client Web server
(iexplorer, netscape
Navigator, mozzila, . . . ) (IIS, Apache)
• FTP Client FTP server
• Telnet Client Telnet server
• ...
• These are all precompiled programs and
may be used to communicate across a
network.
Computer networking/socket/naj/3
What is a Socket?
• Is it like this?

• Yes but these are electrical sockets


– A socket is a place where we can put something
or from that we can get something
– That thing may be electrical power for above
case or information in case of network
programming.
Computer networking/socket/naj/4
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/from
the network via sockets
• In UNIX terminology you can say that it is also a
file, Like file descriptor it is also recognized by a
socket descriptor( a 16 bit integer)
• Sockets are always created in pairs and they are
used to communicate with other sockets
• There are many kinds of sockets like Internet
sockets, UNIX sockets, . . .
Computer networking/socket/naj/5
Sockets
• The socket is the BSD method for
accomplishing interprocess communication
(IPC) in a network.
• That’s why also called BSD sockets.
• There are two important types of internet
sockets
– Stream socket, -- Datagram socket
• Other type of internet sockets are
– Raw socket, -- Sequence packet
We will concentrate on stream and datagram soc.
Computer networking/socket/naj/6
Essential types of sockets
• SOCK_STREAM • SOCK_DGRAM
– TCP – UDP
– reliable delivery – unreliable delivery
– in-order guaranteed – no order guarantees
– connection-oriented – no notion of “connection”
– bidirectional – can send or receive

App
App
3 2
1
socket Dest. 3 2
1
socket Dest

Computer networking/socket/naj/7
Stream Oriented Comm.
Server Client
• Create a Socket
Socket
• Bind it to a local port
bind
• Listen for a incoming
listen connection request

Accept • Connect from a client


Connect
• Accept the request
.
Read Write
• Talk to each other
.
Write Read • Close the socket
Close
. Close
Computer networking/socket/naj/8
How to Program
• We will use Socket API with C programming
in 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 UNIX
systems? Computer networking/socket/naj/9
Data Structures
<netinet/in.h>
struct in_addr{
in_addr_t s_addr;
};
/* 32 bit unsigned net/host id in
network byte order */
//typedef uint32_t in_addr_t;
¾Network byte order is in big-
endian format and host byte
order is in little-endian format
Computer networking/socket/naj/10
Byte orders
Increasing memory
address
Address A+1 Address A
Little-endian byte order High-order byte Low-order byte

MSB 16-bit value LSB

Big-endian byte order High-order byte Low-order byte


Address A Address A+1
Increasing memory
address
Computer networking/socket/naj/11
Byte-ordering
❒ Problem:
❍ different machines / OS’s use different word
orderings
• little-endian: lower bytes first
• big-endian: higher bytes first
❍ these machines may communicate with one another
over the network

Big-Endian
machine Little-Endian
12.40.119.128
128.119.40.12 machine

128 119 40 12 128 119 40 12

Computer networking/socket/naj/12
IPV4 Socket Add Structure
<netinet/in.h>
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 of posix.1g
¾sin_len: length of structure?
included in 4.3 BSD-Reno
¾Sa_family_t: address family of
socket address structure
<sys/socket.h>
Computer networking/socket/naj/13
IPV4 Socket Add Structure
¾sin_family: socket address family
¾AF_INET IPv4 family
¾AF_INET6 IPv6
¾AF_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
Computer networking/socket/naj/14
Ports
• Each host has 65,536 Port 0
ports
Port 1
• Some ports are
reserved for specific
apps called as IANA Port 65535

ports or reserved ports,


(0 – 1024)
– 20,21: FTP • Others are called
– 23: Telnet ephemeral ports( IANA is
– 80: HTTP
silent about it)
• 1024 – 49151 are A socket provides an
called IANA registered interface to address
ports IP:port pair
Computer networking/socket/naj/15
IPV4 Socket Add Structure
• The sin_zero member is unused, but it is set
to 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
Computer networking/socket/naj/16
System Calls
¾Creating a socket
#include<sys/socket.h>
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
Computer networking/socket/naj/17
System Calls(2)
– type: communication type
type Description
SOCK_STREAM stream socket
SOCK_DGRAM datagram socket
SOCK_RAW raw socket
– protocol: specifies protocol, usually set to 0
except for raw sockets (so that socket choose
correct protocol based on type)
– Note:
• not all combination of socket family and type are valid.

Computer networking/socket/naj/18
System Calls(3)
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
• YES are valid but do not have acronyms
• There are also various other values for family and
type 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);
Computer networking/socket/naj/19
System Calls(4)
#include<sys/socket.h>
int bind(int sockfd, const struct sockaddr *myaddr,
socklen_t addrlen);
• ‘bind’ assigns a local protocol address to a
socket
• Local protocol address consists of IP
address along with a port number
• Second argument is a pointer(?) to address
structure
• Third argument is the length(size) of
address structure (32-bit integer)
Computer networking/socket/naj/20
System Calls(5)
• With TCP, calling bind lets us specify a port
number, an IP address, both or neither.
Process specifies Result

IP address Port

wildcard 0 Kernel chooses IP address and


port
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
Computer networking/socket/naj/21
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 chooses
the source IP when socket is connected,
based on outgoing interface.
Computer networking/socket/naj/22
Byte ordering functions
#include <netinet/in.h>
ƒ uint32_t htonl(uint32_t hostlong); it converts the long
integer hostlong from host byte order to network byte
order.
ƒ uint16_t htons(uint16_t hostshort); it converts the short
integer hostshort from host byte order to network byte
order.
ƒ Both returns value in network byte order

ƒ uint32_t ntohl(uint32_t netlong); it converts the long


integer netlong from network byte order to host byte order.
ƒ uint16_t ntohs(uint16_t netshort); it converts the short
integer netshort from network byte order to host byte order.
ƒ Both returns values in host byte order Computer networking/socket/naj/23
System Calls(6)
#include<sys/socket.h>
int listen(int sockfd, int backlog);
• The listen function converts an unconnected
socket into a passive socket, indicating that
the 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 the
maximum number of connection that the
kernel should queue for this socket
listen(sockfd,5); Computer networking/socket/naj/24
System Calls(7)
#include<sys/socket.h>
int connect(int sockfd, const struct sockaddr
*servaddr, socklen_t addrlen);
• Used by a client to connect to a server.
• The connect function initiates TCP’s three-
way handshake(?).
• The function returns only when the
connection is established(0) or when an
error occurs(-1)
• If the connect fails, the socket is no longer
usable and must be closed.
Computer networking/socket/naj/25
TCP connection establishment
Client Server
Socket Socket, bind, 1. The server is in
connect(blocks) S YN listen, accept passive open
J (blocks)
(active open) state
K J+1
, AC 2. The client issues an active
SY NK
open by calling connect.
connect returns I.e it sends a SYN
A CK segment
K+ 1
3. Server acknowledges
client’s SYN sends its own
SYN
4. The client acknowledges the server’s SYN
¾The minimum no of packets required for this exchange is
three; hence is called three-way handshake
Computer networking/socket/naj/26
Errors with connection
• If client receives no response to its SYN segment,
ETIMEDOUT is returned. (SYN is sent in every 6
sec and another 24 sec) If no response is received
after a total of 75 secs, the error is
returned.(4.4BSD)
• if server response is RST, it indicates no
process(port) is waiting for connection and
ECONNREFUSED is returned (hard error)
• If client’s SYN elicits an ICMP destination
unreachable from intermediate router, kernel
saves the message but keeps sending SYNs till 75
sec. After which kernel returns EHOSTUNREACH
or ENETUNEECH.(soft error)
Computer networking/socket/naj/27
System Calls(8)
#include<sys/socket.h>
int accept(int sockfd, struct sockaddr *cliaddr,
socklen_t *addrlen);
• It is called by TCP server to return the next completed
connection 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 address
structure and on return it contains the actual no of
bytes stored by the kernel in the socket address
structure
Computer networking/socket/naj/28
System Calls(8)
• If accept is successful, it returns a new descriptor
that 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 listening
socket, which exists for the life time of the server.
• The kernel creates one connected socket for each
client connection that is accepted.
• When server is finished serving a client,
connected socket for that client is closed
Computer networking/socket/naj/29
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;
Computer networking/socket/naj/30
System Calls(10)
#include<unistd.h>
int 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 read
or write
• But TCP will try to send any data that is already
queued to be sent to other end, and after this the
normal TCP connection termination sequence
takes place.( 4-way handshaking?)
Computer networking/socket/naj/31
Network I/O- Reading
• Connection oriented
int 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 less
int recvfrom(int sockfd, char *buf, int nbytes, int flag,
struct sockaddr *from, int addrlen);
– It receives nbytes(max) from a socket, whose address is
given by the from address structure to the buffer
– Returns no of bytes read successfully from the socket
and –1 on error
Computer networking/socket/naj/32
Network I/O- Writing
• Connection oriented
int 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 less
int sendto(int sockfd, char *buf, int nbytes, int flag,
struct sockaddr *to, int addrlen);
– It sends nbytes(max) to a socket, whose address is
given by the to address structure from the buffer
– Returns no of bytes sent successfully from the socket
and –1 on error
Computer networking/socket/naj/33
References
• W. Richard Stevens, UNIX network programming,
vol 1, PE
• Beej’s Guide to Network Programming using
internet sockets
www.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 programming
ftp://rtfm.mit.edu/pub/usenet/news.answers/unix-
faq
Computer networking/socket/naj/34
Thank You
?
Mail to ajit@silicon.ac.in

Computer networking/socket/naj/35

You might also like