tcp ip sockets
TRANSCRIPT
-
8/2/2019 TCP IP Sockets
1/49
University of Cyprus
Department ofComputer Science
By: Dr. Vasos VassiliouSpring 2009
EPL375: Advanced NetworksTCP/IP Socket Programming
in C
-
8/2/2019 TCP IP Sockets
2/49
Overview
Introduction
TCP/IP Basic
UNIX/C Sockets
UDP Sockets
TCP Sockets
Utility Functions
Other Socket API
Summary
-
8/2/2019 TCP IP Sockets
3/49
Internet Protocol (IP)
Datagram (packet) protocol
Best-effort service
Loss
Reordering
Duplication Delay
Host-to-host delivery(not application-to-application)
-
8/2/2019 TCP IP Sockets
4/49
IP Address
32-bit identifier
Identifies a host interface (not a host)
-
8/2/2019 TCP IP Sockets
5/49
Transport Protocols
Best-effort is not sufficient !!!
Add services on top of IP
User Datagram Protocol (UDP) Data checksum
Best-effort
Transmission Control Protocol (TCP) Data checksum
Reliable byte-stream delivery
Flow and congestion control
-
8/2/2019 TCP IP Sockets
6/49
Identifying the ultimate destination
IP addresses identify hosts
Host has many applications
Ports (16-bit identifier)
194.42.16.25
Port 80 25 23
Application WWW E-mail Telnet
Ports
-
8/2/2019 TCP IP Sockets
7/49
TCP/IP Byte Transport
TCP/IP protocols transports bytes
Application protocol provides semantics
Application
TCP/IP
byte stream
Application
TCP/IP
byte stream
Here are somebytes. I dont
know whatthey mean.
Ill passthese tothe app.It knowswhat to
do.
-
8/2/2019 TCP IP Sockets
8/49
Socket
How does one speak TCP/IP?
Sockets provides interface to TCP/IP
Generic interface for many protocols
-
8/2/2019 TCP IP Sockets
9/49
Socket Types
-
8/2/2019 TCP IP Sockets
10/49
Socket
Identified by protocol and local/remote address/port
Applications may refer to many sockets
Socket abstraction Berkeley Sockets (traditional)
Generic
multiple families address representation independence)
Uses existing I/O programming interface as much as possible
Sockets work with Unix I/O services just like files,pipes
Sockets have special needs: establishing a connection specifying communication endpoint addresses
-
8/2/2019 TCP IP Sockets
11/49
TCP/IP Sockets
Family Type Protocol
TCPPF_INET
SOCK_STREAM IPPROTO_TCP
UDP SOCK_DGRAM IPPROTO_UDP
mySock = socket(family, type, protocol);
TCP/IP-specific sockets
Socket reference
File (socket) descriptor in UNIX
Socket handle in WinSock
-
8/2/2019 TCP IP Sockets
12/49
struct sockaddr
{
unsigned short sa_family; /* Address family (e.g., AF_INET) */
char sa_data[14]; /* Protocol-specific address information */
};
struct sockaddr_in
{
unsigned short sin_family; /* Internet protocol (AF_INET) */
unsigned short sin_port; /* Port (16-bits) */
struct in_addr sin_addr; /* Internet address (32-bits) */
char sin_zero[8]; /* Not used */
};
struct in_addr
{
unsigned long s_addr; /* Internet address (32-bits) */
};
Generic
IP
Specific
sockaddr
sockaddr_in
Family
Family Port
Blob
Internet address Not used
2 bytes 2 bytes 4 bytes 8 bytes
-
8/2/2019 TCP IP Sockets
13/49
Client: Initiates the connection
Server: Passively waits to respond
Clients and Servers
Client: Bob
Hi. Im Bob.
Nice to meet you, Jane.
Server: Jane
Hi, Bob. Im Jane
-
8/2/2019 TCP IP Sockets
14/49
Functions needed
Specify local and remote communication endpoints
Initiate a connection
Wait for incoming connection
Send and receive data
Terminate a connection gracefully Error handling
-
8/2/2019 TCP IP Sockets
15/49
TCP Client/Server Interaction
Client
1. Create a TCP socket
2. Establish connection
3. Communicate
4. Close the connection
Server
1. Create a TCP socket2. Assign a port to socket
3. Set socket to listen
4. Repeatedly:
a. Accept new connectionb. Communicate
c. Close the connection
Server starts by getting ready to receive client connections
-
8/2/2019 TCP IP Sockets
16/49
Creating a Socket
int socket(int family, int type, int proto)
system call returns a socket descriptor(small integer); -1on error
allocates resources needed for a communicationendpoint;
does not deal with endpoint addressing family specifies the protocol family
AF_INET for TCP/IP
type specifies the type of service(communication)
SOCK_STREAM, SOCK_DGRAM
protocol specifies the specific protocol
usually 0 which means the default
-
8/2/2019 TCP IP Sockets
17/49
Declaration for socket function
-
8/2/2019 TCP IP Sockets
18/49
Specifying an Endpoint Address
Remember that the sockets API is generic
There must be a generic way to specify endpoint addresses
TCP/IP requires an IP address and a port number for eachendpoint address.
Other protocol suites(families) may use other schemes.
Generic socket addresses(The C function that make up the sockets APIexpect structures of type sockaddr.) :struct sockaddr {
unsigned short sa_family; //specifies the address type
char sa_data[14]; //specifies the address value
};
-
8/2/2019 TCP IP Sockets
19/49
Assigning an address to a socket
int bind(int socket, (struct sockaddr *) address,
int address_length); The bind() system call is used to assign an address to an
existing socket.
bind returns 0 if successful or -1 on error
Example:struct sockaddr_in sin;int s;s = socket(AF_INET, SOCK_DGRAM, 0);
sin.sin_family = AF_INET;sin.sin_port = htons(9999);sin.sin_addr.s_addr = INADDR_ANY;bind(s, (struct sockaddr *)&sin, sizeof(sin));
-
8/2/2019 TCP IP Sockets
20/49
listen() connect() -- TCP Sockets
int listen(int socket, int qlength)
allows servers to prepare a socket for incoming connections puts the socket in a passive mode ready to accept connections
informs the OS that the protocol software should enqueue multiplesimultaneous requests that arrive at the socket
applies only to sockets that have selected reliable stream delivery
service
int connect(int, struct sockaddr *dest_addr, int);
binds a permanent destination to a socket
changes the socket state from unconnected stateto connected state
The semantics of connect depend on the underlaying protocol TCP connection (AF_INET, reliabe stream delivery service)
just store the destination address locally (connectionless)
-
8/2/2019 TCP IP Sockets
21/49
accept() -- TCP Sockets
int accept(int, struct sockaddr * addr, int *
addrlen) needs to wait for a connection
blocks until a connection request arrives
addrlen is a pointer to an integer; when a request arrives , the system fills in argument addr withthe address of the client that has placed the request and setsaddrlen to the length of the address.
system creates a new socket, returns the new socket descriptor
-
8/2/2019 TCP IP Sockets
22/49
send() and recv() -- TCP Sockets
int send(int s, const char *msg, int len, int flags)
connected socket
argument flags controls the transmission.
allows the sender to specify that the message should be sentout-of- band messages correspond to TCPs urgent data
allows the caller to request that the message be sent withoutusing local routine tables (take control of routine)
int recv(int s, char *buf, int len, int flags)
connected socket
argument flags allow the caller to control the reception
look ahead by extracting a copy of the next incoming messagewithout removing the message from the socket
-
8/2/2019 TCP IP Sockets
23/49
close() and shutdown()
close(int socket)
For UDP sockets, this will release the ownership on thelocal port that is bound to this socket
For TCP, this will initiate a two-way shutdown betweenboth hosts before giving up port ownership.
shutdown(int socket, int how)
f the how field is 0, this will disallow further reading(recv) from the socket.
If the how field is 1, subsequent writes (send) will bedisallowed. The socket will still need to be passed toclose.
Relationship Between Sockets and
-
8/2/2019 TCP IP Sockets
24/49
Relationship Between Sockets andFile Descriptors Socket handles are integer values. In UNIX, socket handles
can be passed to most of the low-level POSIX I/Ofunctions.
read(s, buffer, buff_length); //s could be a file descriptor too
write(s, buffer, buff_length) ;
Calling read on an open socket is equivalent to recv if the socket is UDP, then information about the sender of the
datagram will not be returned
Similarly the write function call is equivalent to send
UDP sockets may call connect to use send and write
use the socket library functions instead of the file I/Oequivalents.
Socket interface for Connectionless
-
8/2/2019 TCP IP Sockets
25/49
Socket interface for ConnectionlessIterative Server
-
8/2/2019 TCP IP Sockets
26/49
TCP Client/Server Interaction
Client1. Create a TCP socket
2. Establish connection
3. Communicate
4. Close the connection
Server1. Create a TCP socket
2. Bind socket to a port
3. Set socket to listen
4. Repeatedly:
a. Accept new connection
b. Communicate
c. Close the connection
/* Create socket for incoming connections */if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");
-
8/2/2019 TCP IP Sockets
27/49
TCP Client/Server Interaction
echoServAddr.sin_family = AF_INET; /* Internet address family */
echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY);/* Any incoming interface */echoServAddr.sin_port = htons(echoServPort); /* Local port */
if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)DieWithError("bind() failed");
Client1. Create a TCP socket
2. Establish connection
3. Communicate
4. Close the connection
Server1. Create a TCP socket
2. Bind socket to a port
3. Set socket to listen
4. Repeatedly:
a. Accept new connection
b. Communicate
c. Close the connection
-
8/2/2019 TCP IP Sockets
28/49
TCP Client/Server Interaction
/* Mark the socket so it will listen for incoming connections */if (listen(servSock, MAXPENDING) < 0)
DieWithError("listen() failed");
Client1. Create a TCP socket
2. Establish connection
3. Communicate
4. Close the connection
Server1. Create a TCP socket
2. Bind socket to a port
3. Set socket to listen
4. Repeatedly:
a. Accept new connection
b. Communicate
c. Close the connection
-
8/2/2019 TCP IP Sockets
29/49
TCP Client/Server Interaction
for (;;) /* Run forever */
{clntLen = sizeof(echoClntAddr);
if ((clntSock=accept(servSock,(struct sockaddr *)&echoClntAddr,&clntLen)) < 0)DieWithError("accept() failed");
Client1. Create a TCP socket
2. Establish connection
3. Communicate
4. Close the connection
Server1. Create a TCP socket
2. Bind socket to a port
3. Set socket to listen
4. Repeatedly:
a. Accept new connection
b. Communicate
c. Close the connection
-
8/2/2019 TCP IP Sockets
30/49
TCP Client/Server Interaction
Server is now blocked waiting for connection from a client
Later, a client decides to talk to the server
Client1. Create a TCP socket
2. Establish connection
3. Communicate
4. Close the connection
Server1. Create a TCP socket
2. Bind socket to a port
3. Set socket to listen
4. Repeatedly:
a. Accept new connection
b. Communicate
c. Close the connection
-
8/2/2019 TCP IP Sockets
31/49
TCP Client/Server Interaction
/* Create a reliable, stream socket using TCP */if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");
Client1. Create a TCP socket
2. Establish connection
3. Communicate
4. Close the connection
Server1. Create a TCP socket
2. Bind socket to a port
3. Set socket to listen
4. Repeatedly:
a. Accept new connection
b. Communicate
c. Close the connection
-
8/2/2019 TCP IP Sockets
32/49
TCP Client/Server Interaction
echoServAddr.sin_family = AF_INET; /* Internet address family */echoServAddr.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */echoServAddr.sin_port = htons(echoServPort); /* Server port */
if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)DieWithError("connect() failed");
Client1. Create a TCP socket
2. Establish connection
3. Communicate
4. Close the connection
Server1. Create a TCP socket
2. Bind socket to a port
3. Set socket to listen
4. Repeatedly:
a. Accept new connection
b. Communicate
c. Close the connection
-
8/2/2019 TCP IP Sockets
33/49
TCP Client/Server Interaction
if ((clntSock=accept(servSock,(struct sockaddr *)&echoClntAddr,&clntLen)) < 0)DieWithError("accept() failed");
Client1. Create a TCP socket
2. Establish connection
3. Communicate
4. Close the connection
Server1. Create a TCP socket
2. Bind socket to a port
3. Set socket to listen
4. Repeatedly:
a. Accept new connection
b. Communicate
c. Close the connection
-
8/2/2019 TCP IP Sockets
34/49
TCP Client/Server Interaction
echoStringLen = strlen(echoString); /* Determine input length */
/* Send the string to the server */if (send(sock, echoString, echoStringLen, 0) != echoStringLen)
DieWithError("send() sent a different number of bytes than expected");
Client1. Create a TCP socket
2. Establish connection
3. Communicate
4. Close the connection
Server1. Create a TCP socket
2. Bind socket to a port
3. Set socket to listen
4. Repeatedly:
a. Accept new connection
b. Communicate
c. Close the connection
-
8/2/2019 TCP IP Sockets
35/49
TCP Client/Server Interaction
/* Receive message from client */if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
DieWithError("recv() failed");
Client1. Create a TCP socket
2. Establish connection
3. Communicate
4. Close the connection
Server1. Create a TCP socket
2. Bind socket to a port
3. Set socket to listen
4. Repeatedly:
a. Accept new connection
b. Communicate
c. Close the connection
-
8/2/2019 TCP IP Sockets
36/49
TCP Client/Server Interaction
close(sock); close(clntSocket)
Client1. Create a TCP socket
2. Establish connection
3. Communicate
4. Close the connection
Server1. Create a TCP socket
2. Bind socket to a port
3. Set socket to listen
4. Repeatedly:
a. Accept new connection
b. Communicate
c. Close the connection
-
8/2/2019 TCP IP Sockets
37/49
TCP Tidbits
Clientsend(Hello Bob)
recv() -> Hi Jane
Server
recv() -> Hello
recv() -> Bob
send(Hi )
send(Jane)
Client must know the servers address and port
Server only needs to know its own port
No correlation between send() and recv()
-
8/2/2019 TCP IP Sockets
38/49
Closing a Connection
close() used to delimit communication
Analogous to EOF
Echo Clientsend(string)
while (not received entire string)
recv(buffer)
print(buffer)
close(socket)
Echo Server
recv(buffer)
while(client has not closed connection
send(buffer)
recv(buffer)
close(client socket)
-
8/2/2019 TCP IP Sockets
39/49
Byte-order Transformations
Byte ordering is a function of machine architecture
Intel: little-endian Sparc, PowerPC: big-endian
Network order: big-endian
The byte order for the TCP/IP protocol suite is bigendian.
-
8/2/2019 TCP IP Sockets
40/49
Big-endian byte order
-
8/2/2019 TCP IP Sockets
41/49
Little-endian byte order
-
8/2/2019 TCP IP Sockets
42/49
Network Byte Order Functions
-
8/2/2019 TCP IP Sockets
43/49
Network Byte Order Functions
Functions:
u_long m =ntohl(u_long m) network-to-host byte order, 32 bit
u_long m =htonl(u_long m)
host-to-network byte order, 32 bit
ntohs(),htons() short (16 bit)
Example:
struct sockaddr_in sin;sin.sin_family = AF_INET;
sin.sin_port = htons(9999);
sin.sin_addr.s_addr = inet_addr;
-
8/2/2019 TCP IP Sockets
44/49
Address transformation
-
8/2/2019 TCP IP Sockets
45/49
unsigned int inet_addr(char *str)
str represents an IP address(dotted-quad notation); inet_addr willreturn it's equivalent 32-bit value in network byte order.
This value can be passed into the sin_addr.s_addr field of asocketaddr_in structure
-1 is returned if the string can not be interpreted
char *inet_ntoa(struct in_addr ip) Converts the 32-bit value which is assumed to be in network byte
order and contained in ip to a string
The pointer returned by inet_ntoa contains this string. However,subsequent calls to inet_ntoa will always return the same pointer, socopying the string to another buffer is recommended before callingagain.
Address transformation
-
8/2/2019 TCP IP Sockets
46/49
Obtaining Information About Hosts, etc.
struct hostent *hptr; /*includes host address in
binary*/hptr=gethostbyname(char *name);
Ex.:gethostbyname(www.csc.ncsu.edu);
Struct hostent *hptr;
hptr=gethostbyaddr(char *addr,int addrlen, intaddrtype);
Ex: gethostbyaddr(&addr, 4, AF_INET);
http://www.csc.ncsu.edu/http://www.csc.ncsu.edu/ -
8/2/2019 TCP IP Sockets
47/49
Obtaining Information About Hosts, etc.
int inet_addr(char *dotdecimal);
Ex.: sin_addr = inet_addr(152.14.51.129);
struct servent *sptr; /* includes port and protocol */
sptr=getservbyname(char *name, char *proto);
Ex.: getservbyname(smtp, tcp);
struct protoent *pptr; /* includes protocol number */
pptr=getprotobyname(char *name);Ex.: getprotobyname(tcp);
-
8/2/2019 TCP IP Sockets
48/49
Others Include files
#include ;
#include ;
#include ;
#include ;
#include ;
#include ;
#include ;
#include ;
#include ;
#include
-
8/2/2019 TCP IP Sockets
49/49
Summary
TCP/IP basic
UNIX/C Sockets
socket() ; bind() ; connect() ; listen() ; accept() ;sendto() ; recvfrom(); send() ; recv() ; read() ; write();
some utility functions