PowerPoint Presentation
UNIT-3 BSD SocketsTCP/IP Model, BSD Sockets Overview, TCP
Sockets and Client/Server, UDP Sockets and Client/Server, Out of
Band Data, Raw Sockets, PING & TRACEROUTE Programs, Routing,
Multicasting using UDP SocketsAmardeep Singh
PatelM.Tech(CSE)1402710502TCP/IP ModelTCP/IP Model
A highly standardized protocol used widely on the
Internet.Standards area available in the form of RFC documents
Request For Comments (RFC)Standards are overseen by the Internet
Engineering Task Force (IETF)There are four layers of the TCP/IP
reference model (DARPA model as named by the US Government
Agency)The ISO-OSI reference model is composed of seven layers
Note that the ISO/OSI model is more widely used and accepted but
the TCP/IP model is easy to comprehend
TCP/IP Layers
Network interface layerInternet layerHost-to-host transport
layerApplication layer
Network interface layer
Responsible for sending and receiving TCP/IP packets on the
network medium (physical/Data Link)Applicable LAN
technologiesEthernet, Token Ring, FDDI etc.Applicable WAN
technologiesX.25 (old), Frame Relay, ATM etc.Note that some
technologies such as ATM and FDDI may be used at both the WAN and
the LAN levels
Data Link Layer + Physical Layer = Network interface
layerInternet layer
PackagingAddressingRouting
7Host-to-host transport layer
Acknowledgment of receiptsRecovery of packetsFlow controlIn
essence, it engages in host-to-host transportation of data packets
and the delivery of them to the application layer
Application layer
Provides applications with the ability to access the services of
the other layersNew protocols and services are always being
developed in this category
BSD Sockets OverviewThe Berkeley Sockets 4.4 API (Applications
Programmer Interface) is a set of standard function calls made
available at the application level. These functions allow
programmers to include Internet communications capabilities in
their products.The Berkeley Sockets API (also frequently referred
to as simply `sockets') was originally released with 4.2BSD in
1983. Enhancements have continued through the 4.4BSD systems.
Berkeleybased code can be found in many different operating
systems, both commercial and public domain, such as BSD/OS,
FreeBSD, NetBSD, OpenBSD, and UnixWare 2.x. Other popular operating
systems such as Solaris and Linux employ the standard sockets
interface, though the code was written from scratch.Other sockets
APIs exist, though Berkeley Sockets is generally regarded as the
standard. Two of the most common APIs are Winsock and TLI.Winsock
(Windows Sockets) was developed for the Microsoft Windows platform
in 1993, and is based significantly on the BSD interface.BSD
Sockets generally relies upon client/server architecture.Common
Socket Callssocket()A socket, in the simplest sense, is a data
structure used by the Sockets API. When the user calls this
function, it creates a socket and returns reference a number for
that socket. That reference number, in turn, must be used in future
calls.
bind()This call allows a user to associate a socket with a
particular local port and IP address. In the case of a server (see
listen and accept below), it allows the user to specify which port
and IP address incoming connections must be addressed to. For
outgoing connection requests (see connect below), it allows the
user to specify which port the connection will come from when
viewed by the other host.13listen()This function prepares the given
socket to accept incoming TCP requests. It must be called before
accept().accept()This function detects incoming connection requests
on the listening socket. In blocking mode, this call will cause a
task to sleep until a connection request is received. In
nonblocking mode, this call will return TM_EWOULDBLOCK indicating
that no connection request is present and that accept must be
called again. connect()When a user issues a connect command, the
stack creates a connection with another host. Before connect can
instruct the stack to establish a connection, the user must pass a
socket and a sockaddr_in structure containing the destination IP
address and port.send()This call allows a user to send data over a
connected socket. Unlike sendto(), this socket must be connected.
Because the socket is already connected, it is not necessary to
specify the destination address (the estination address was set in
accept or connect). send can be used for either UDP or TCP
data.sendto()Unlike send(), sendto requires users to specify the
destination port and address.recv()This function allows the user to
receive data on the connected socket. recv can be used for either
TCP or UDP.recvfrom()This function allows the user to receive data
from a specified UDP socket (whether or not it is connected). It
may not be used for TCP sockets, as they require a
connection.close()This function closes (read: deletes) a socket
that has been allocated with the socket call. If the socket is
connected, it closes the connection before deleting it. Because the
close call is frequently used for more than one purpose (closing
open files, for example), it is renamed tfClose() in the Treck
stack to avoid conflicts with the preexisting function.TCP Sockets
and
Client/Serversocket()bind()listen()accept()socket()connect()send()recv()Client(Block
until connection)Handshakerecv()send()Data (request)Data
(reply)close()End-of-Filerecv()close()well-knownportServersocket()int
socket(int family, int type, int protocol);Create a socket, giving
access to transport layer service.family is one ofAF_INET (IPv4),
AF_INET6 (IPv6), AF_LOCAL (local Unix),AF_ROUTE (access to routing
tables), AF_KEY (new, for encryption)type is one ofSOCK_STREAM
(TCP), SOCK_DGRAM (UDP)SOCK_RAW (for special IP packets, PING, etc.
Must be root)setuid bit (-rws--x--x root 1997 /sbin/ping*)protocol
is 0 (used for some raw socket options)upon success returns socket
descriptorInteger, like file descriptorReturn -1 if failure
bind()int bind(int sockfd, const struct sockaddr *myaddr,
socklen_t addrlen);Assign a local protocol address (name) to a
socket.sockfd is socket descriptor from socket()myaddr is a pointer
to address struct with:port number and IP addressif port is 0, then
host will pick ephemeral portnot usually for server (exception RPC
port-map)IP address != INADDR_ANY (unless multiple nics) addrlen is
length of structurereturns 0 if ok, -1 on errorEADDRINUSE (Address
already in use)
listen()int listen(int sockfd, int backlog);Change socket state
for TCP server.sockfd is socket descriptor from socket()backlog is
maximum number of incomplete connectionshistorically 5rarely above
15 on a even moderate Web server!Sockets default to active (for a
client)change to passive so OS will accept connection
accept()int accept(int sockfd, struct sockaddr cliaddr,
socklen_t *addrlen);Return next completed connection.sockfd is
socket descriptor from socket()cliaddr and addrlen return protocol
address from clientreturns brand new descriptor, created by OSnote,
if create new process or thread, can create concurrent server
close()int close(int sockfd); Close socket for use.
sockfd is socket descriptor from socket()closes socket for
reading/writingreturns (doesnt block)attempts to send any unsent
datasocket option SO_LINGERblock until data sentor discard any
remaining datareturns -1 if error
Sending and Receivingint recvfrom(int sockfd, void *buff, size_t
mbytes, int flags, struct sockaddr *from, socklen_t *addrlen);int
sendto(int sockfd, void *buff, size_t mbytes, int flags, const
struct sockaddr *to, socklen_t addrlen);
Same as recv() and send() but for addrrecvfrom fills in address
of where packet came fromsendto requires address of where sending
packet to
UDP Sockets and Client/ServerUDP
Client-Serversocket()bind()recvfrom()Serversocket()sendto()recvfrom()Client(Block
until receive datagram)sendto()Data (request)Data
(reply)close()well-knownport- No handshake- No simultaneous close-
No fork()/spawn() for concurrent servers!Sending and Receivingint
recvfrom(int sockfd, void *buff, size_t mbytes, int flags, struct
sockaddr *from, socklen_t *addrlen);int sendto(int sockfd, void
*buff, size_t mbytes, int flags, const struct sockaddr *to,
socklen_t addrlen);Same as recv() and send() but for addrrecvfrom
fills in address of where packet came fromsendto requires address
of where sending packet to
connect() with UDPRecord address and port of peerdatagrams
to/from others are not alloweddoes not do three way handshake, or
connectionconnect a misnomer, here. Should be setpeername()Use
send() instead of sendto()Use recv() instead of recvfrom()Can
change connect or unconnect by repeating connect() call(Can do
similar with bind() on receiver)
Out of Band DataIntroductionOut-of-band dataExpedited
dataNotification should be sent before any normal (in-band) data
that is already queued to be sentHigher priority than normal
dataOut-of-band data mapped onto existing connection (instead of
using two connections)UDP has no implementation of out-of-band
dataTCP has its own flavor of out-of-band data
TCP Out-of-Band Data 1/5TCP does not have a true out-of-band
data modeTCP provides an urgent modeN bytes in TCP socket send
bufferProcess writes a single byte of out-of-band data send
(fd,a,1,MSG_OOB);
1NFirst byte to sendlast byte to sendSocket send
buffer1NOOBSocket send bufferFirst byte to sendlast byte to sendTCP
Urgent PointerTCP Out-of-Band Data 2/5Next segment sent by TCP will
have URG flag set in TCP headerUrgent offset in TCP header points
to byte following the out-of-band byteAdd urgent offset to sequence
number field to obtain value of urgent pointerSegment may or may
not contain the byte labeled as OOBDepends on number of bytes ahead
of it, segment size, and current receiver window
1NFirst byte to sendlast byte to sendSocket send
buffer1NOOBSocket send bufferFirst byte to sendlast byte to sendTCP
Urgent PointerTCP Out-of-Band Data 3/5TCP header indicates that
sender has entered urgent mode (actual byte of data referred to by
urgent pointer need not be sent)IF sending TCP is stopped by flow
controlUrgent notification is sent without any dataOne of the
reasons why applications use TCPs urgent modeIf multiple bytes are
sent out-of-bandsend (fd,abc,3,MSG_OOB);Urgent pointer points one
beyond the final byte last byte is considered the out-of-band
byteTCP Out-of-Band Data 4/5Receivers response to out-of-band
dataTCP Checks urgent pointer to see if it refers to new
out-of-band data (TCP can send multiple segments containing URG
flag, but referring to same byte of data)Only first segment causes
receiving process to be notified SIGURG signal delivered to socket
ownerIf process blocked in a call to select (waiting for an
exception condition), select returnsOnly one OOB mark, if a new OOB
byte arrives before old is read, old byte is discardedTCP
Out-of-Band Data 5/5Receivers response to out-of-band dataActual
OOB byte can be pulled out-of-band or left inlineSO_OOBINLINE
socket option (by default not set)Byte not placed in socket receive
bufferByte placed into a separate one-byte out-of-band buffer for
this connectionTo read from that buffer, use recv and specify
MSG_OOB flagIf SO_OOBINLINE socket option is setByte left in normal
socket receive bufferProcess knows when it reaches this byte of
data by checking the out-of-band mark for this connectionRaw
SocketsWhat are Raw Sockets?Allows you to bypass the TCP/UDP
layers.
Send/receive your own packets, with your own headers.
You need to do all protocol processing at user-level.Typical
UsesICMP messagesping generates ICMP echo requests and received
ICMP echo replies.
Routing protocolsgated implements OSPF routing protocol.Uses IP
packets with protocol ID 89 not supported by kernel.
Hacking Generating your own TCP/UDP packets with spoofed
headersRaw socket creationOnly root can open a raw socket.
sockfd = socket(AF_INET, SOCK_RAW, proto)
where proto is IPPROTO_RAW, IPPROTO_ICMP etc.Raw socket outputAs
usual sendto(), sendmsg() etc.
IP_HDRINCL option Specifies whether the process or the kernel
builds the IP header.
/* allow process to build IP header */int on=1; setsockopt(
sockfd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on))Raw socket
inputNormally using recvfrom()Conditions for a packet to match raw
socket
If protocol parameter was specified, only packets with that
protocol value are delivered.
If bind() was called on raw socket, only packets destined to
bound IP address are delivered.
If connect() was called, only packets from connected address are
delivered.Which protocol types are delivered?TCP and UDP never
reach raw socketsKernel IP stack handles theseLinux implementation
is an exception.
All ICMP exceptICMP echo requestTimestamp requestMask
request
All IGMP
All other protocols that kernel doesn't understandSuch as
OSPFRouting, Multicasting using UDP Sockets
Multicast Basic ConceptsPrevious TCP/UDP examples are all
unicastUnicast: point to point communicationBroadcast: packets are
sent to all IP supports broadcasting, but the use of broadcasts is
strictly limited. Protocols require broadcasts only when there is
no alternative Routers limit broadcasts to the local network or
subnet, preventing broadcasts form reaching the Internet at large.
Multicast: send packets to many different hosts, but not to
everyone.Think of these: a single mail sends to 6 million addresses
a real-time video stream goes to 6 million Internet user Internet
crash??? There is no reason to send a video stream to hosts that
are not interested in it.Examples: need multicast Video
conferencing: send audio-video streams to a select group of people
DNS routers News group
Multicast: think as a group like a public meeting People can
come and go as they please send messages to the group and all the
people in the group will get the messages. People not in the group
will not be affectedMulticast to 1000 clients Broadcast to the
world (inefficient) 1000 point-to-point unicasts Connection tree
(not flexible)
Multicast Socketpublic class MulticastSocket extends
DatagramSocketMulticastSocket inherits from
DatagramSocketConstructorMulticastSocket(): Create a multicast
socket.(i.e. use asynymous port)MulticastSocket(intport):Create a
multicast socket and bind it to a specific port.Multicast Socket:
communication with a multicast groupMulticast Key operationsJoin a
multicast groupSend data to the members of the groupReceive data
from the groupLeave the multicast groupvoid
joinGroup(InetAddressmcastaddr)Joins a multicast group.Its behavior
may be affected by setInterface.Example page 463-464void
send(DatagramPacketp, bytettl)Sends a datagram packet to the
destination, with a TTL (time- to-live) other than the default for
the socket.default time to live: 1