TCP Sockets
TCP Sockets
Chapter 4
UNIX Network Programming
Vol. 1, Second Ed. Stevens
user user
kernel kernel
Socket Socket
Underlying Underlying
communication communication
Protocols Protocols
Communications
network
Copyright ©2000 The McGraw Hill Companies Leon-Garcia & Widjaja: Communication Networks Figure 2.16
bind()
listen()
Client
accept()
socket()
data write()
read()
write() data
read()
close()
close()
Copyright ©2000 The McGraw Hill Companies Leon-Garcia & Widjaja: Communication Networks Figure 2.17
sendto() data
recvfrom()
close()
close()
Copyright ©2000 The McGraw Hill Companies Leon-Garcia & Widjaja: Communication Networks Figure 2.18
Networks: TCP/IP sockets 5
System Calls for Elementary TCP Sockets
#include <sys/types.h>
#include <sys/socket.h>
socket Function
int socket ( int family, int type, int protocol );
int connect (int sockfd, const struct sockaddr *servaddr, socklen_t addrlen);
The socket address structure must contain the IP address and the port
number for the connection wanted.
In TCP connect initiates a three-way handshake. connect returns when the
connection is established or when an error occurs.
returns on success: 0
on error: -1
Example:
if ( connect (sockfd, (struct sockaddr *) &servaddr, sizeof (servaddr)) != 0)
err_sys(“connect call error”);
Networks: TCP/IP sockets 7
bind Function
int bind (int sockfd, const struct sockaddr *myaddr, socklen_t addrlen);
The server will have one connected socket for each client
connection accepted.
When the server is finished with a client, the connected
socket must be closed.
Example:
sfd = accept (s, NULL, NULL);
if (sfd == -1) err_sys (“accept error”);
Networks: TCP/IP sockets 11
close Function