TCP/IP Sockets API
Download
Report
Transcript TCP/IP Sockets API
Sockets API
Developing Applications using the
Sockets API
IP is the underlying Network
Layer Protocol
Two tranport layer protocols
Both End-to-end transport protocols
UDP – User Datagram Protocol
Datagrams
Unreliable
No connection
Best Effort
Application must deal with loss
IP is the underlying Network
Layer Protocol
Two tranport layer protocols
TCP – Transmission Control Protocol
Connection Oriented
Reliable Byte Stream
Detects/recovers from errors
Conceptually similar to file I/O
Sockets – two sides
Every TCP/UDP link has two sides
Client
Server
Creating and destroying
Sockets
int socket(int protocolFamily, int type, int protocol)
Returns socket handle
ProtocolFamily = family of protocols to be used – PF_INET
Type = type of protocol
SOCK_DGRAM for UDP
SOCK_STREAM for TCP
Protocol = specific protocol to be used
IPPROTO_UDP for UDP
IPPROTO_TCP for TCP
Creating and destroying
Sockets
int close(int socket)
Closes socket identified by socket
returns 0 on success
-1 on failure
Addresses
See other slides
Connecting – client side
int connect(int socket, struct sockaddr
*foreignAddr, unsigned int addLength)
Uses created socket to connect to foreign
host/application
socket = socket handle created by call to socket
foreignAddr = address of the server of the type
sockaddr
addLength = length of the foreignAddr address
Communicating
int send(int socket, const void *msg, unsigned int
msgLength, int flags)
int recv(int socket, const void *rcvBuff, unsigned int
buffLen, int flags)
socket = socket handle
msg = pointer to outgoing message
rcvBuff = buff for incoming message
msgLength = N of bytes of msg to be sent
buffLen = size of buffer, max byte to receive
flags = control default behavior set to 0
TCP - Server side
Server is passive
sits and waits for connection from client(s)
replace call to connect with listen/accept
Listening
int listen(int socket, int qlimit)
listening (and blocks) for connection
from “calling” client
socket = existing socket handle
qlimit = max number of outstanding
connect requests
returns 0 if success , -1 if failure
Making a connection
int accept(int socket, struct sockaddr
*clientAddr, unsigned int *addLen)
Accepts connection request
socket = existing socket
*clientAddr = pointer to address struct of
connecting client
*addLen = pointer to length of clientAddr
structure