Download Chapter 4 Socket Programming Preliminary

Document related concepts

AppleTalk wikipedia , lookup

TCP congestion control wikipedia , lookup

Dynamic Host Configuration Protocol wikipedia , lookup

Parallel port wikipedia , lookup

IEEE 1355 wikipedia , lookup

Internet protocol suite wikipedia , lookup

Recursive InterNetwork Architecture (RINA) wikipedia , lookup

I²C wikipedia , lookup

Remote Desktop Services wikipedia , lookup

Lag wikipedia , lookup

Cracking of wireless networks wikipedia , lookup

Zero-configuration networking wikipedia , lookup

UniPro protocol stack wikipedia , lookup

Real-Time Messaging Protocol wikipedia , lookup

Transcript
Data Communications and
Networking
Socket Programming Part I:
Preliminary
Reading:
Appendix C - Sockets: A Programmer’s Introduction
Data and Computer Communications, 8th edition
By William Stallings
Reference:
Internetworking With TCP/IP, Volume III: Client-Server
Programming And Applications, Windows Socket Version
By Douglas E. Comer and David L. Stevens.
1
Learning Outcomes
• Knowledge
—Explain the principles of network programming
—Explain the client-server model
—Get familiar with WinSock APIs
• Skills
—Design and develop the client side of client-server network
applications using socket programming
2
Outline
• Client Server Model
• Concept of Socket
• Address Structures
—Byte order
• WinSock API
• Client Software Design
—TCP
—UDP
3
Client Server Model
• TCP/IP allows two application programs to pass data
back and forth
—The applications can execute on the same machine or on
different machines
• How to organize the application programs?
—Client-server paradigm is the most popular model
• The communication applications are divided into two categories:
client and server
• Client-server paradigm uses the direction of
initiation to categorize whether a program is a client
or server.
4
Client Server Model (Cont.)
• An application that initiates the communication is called a
client
— E.g., Web browser, FTP client, Telnet client, Email client
— The client contacts a server, sends a request, and awaits a response
• An application that waits for incoming communication
requests from clients is called a server
— E.g., Web server, FTP server, Telnet server, SMTP server
— The server receives a client’s request, performs the necessary
computation, and returns the result to the client
— Remark: A server is usually designed to provide service to multiple
clients
• How ???
5
Client Server Model (Cont.)
Remark:
Client Programs:
Web browsers
Because the Web servers
and Web browsers are
designed based on HTTP,
different Web browsers can
communicate with all
kinds of Web servers.
6
Time Service: An Example
• Time service: based on Time Protocol (RFC868)
— http://www.faqs.org/rfcs/rfc868.html
— The Time service sends back to the originating source the time in
seconds since midnight on January first 1900
— Can use TCP or UDP
• Time protocol (when using UDP):
—
—
—
—
Server: Listen on port 37.
Client: Send an empty datagram to port 37.
Server: Receive the empty datagram.
Server: Send a datagram containing the time as a 32 bit binary
number.
— Client: Receive the time datagram.
7
Time Service: Server Program
#include <stdio.h> #include <stdlib.h>
#include <time.h> #include <string.h>
#include <stdarg.h> #include <winsock2.h>
#define SA struct sockaddr
#define MAXLINE 4096
#define S_PORT 37
#define WINEPOCH 2208988800
int main(int argc, char **argv)
{
WSADATA wsadata;
struct sockaddr_in servaddr, cliaddr;
char buff[MAXLINE];
time_t ticks; /* current time */
int n, len;
SOCKET s;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0)
errexit("WSAStartup failed\n");
/* Fill up the servaddr */
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family
= AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port
= htons(S_PORT);
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s == INVALID_SOCKET)
errexit("cannot create socket: error number %d\n",
WSAGetLastError());
/* Bind the servaddr to socket s */
if (bind(s, (SA *) &servaddr, sizeof(servaddr)) ==
SOCKET_ERROR)
errexit("can't bind to port %d: error number %d\n", S_PORT,
WSAGetLastError());
for ( ; ; ) {
len = sizeof(SA);
if (n = recvfrom(s, buff, sizeof(buff), 0, (SA *)&cliaddr,
&len) == SOCKET_ERROR)
errexit("recvfrom error: error number %d\n",
WSAGetLastError());
time(&ticks); /* returns the number of seconds elapsed
since midnight of January 1, 1970 */
ticks = htonl((u_long)(ticks + WINEPOCH));
sendto(s, (char *)&ticks, sizeof(ticks), 0, (SA *)&cliaddr,
sizeof(cliaddr));
} /* end of for loop */
}
8
Time Service: Client Program
#include <stdio.h> #include <stdlib.h>
#include <time.h> #include <string.h>
#include <stdarg.h> #include <winsock2.h>
#define SA struct sockaddr
#define MAXLINE 4096
#define S_PORT 37
#define WINEPOCH 2208988800
int main(int argc, char **argv)
{
WSADATA wsadata;
SOCKET s;
int n, len;
time_t now;
struct sockaddr_in servaddr;
/* Must initialize the socket DLL first */
if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0)
errexit("WSAStartup failed\n");
errexit("socket error: error number %d\n",
WSAGetLastError());
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(S_PORT);
if ( (servaddr.sin_addr.s_addr = inet_addr(argv[1])) ==
INADDR_NONE)
errexit("inet_addr error: error number %d\n",
WSAGetLastError());
sendto(s, NULL, 0, 0, (SA *)&servaddr, sizeof(servaddr));
len = sizeof(SA);
n = recvfrom(s, (char *)&now, sizeof(now), 0, (SA
*)&servaddr, &len);
if (n == SOCKET_ERROR)
errexit("recvfrom failed: error number %d\n",
WSAGetLastError());
now = ntohl((u_long)now);
now -= WINEPOCH;
printf("%s", ctime(&now));
if (argc != 2)
errexit("usage: daytimeudpcli <IPaddress>");
/* Create a socket, and check the return value */
if ( (s = socket(AF_INET, SOCK_DGRAM, 0)) ==
INVALID_SOCKET )
WSACleanup();
return 0;
}
9
How to Write Network
Applications?
• TCP/IP is implemented inside the OS
• OS exports the TCP/IP functionalities through
SOCKET APIs
—API: Application Program Interface
—A set of functions
• Programmers develop network applications by using
SOCKET APIs
• To learn SOCKET programming
—Learn some data structures
—Learn the socket APIs
—Learn multi-threading
10
Socket Abstraction
• “Socket” is an interface between applications and the
network services provided by OS
• An application sends and receives data through a socket
Application
SOCKET API
TCP/IPv4
TCP/IPv6
UNIX
11
Socket Abstraction (Cont.)
Process B
Process A
data
data
data
socket
socket
12
Socket Abstraction (Cont.)
Browser A
Web Server
socket
Browser B
socket
socket
Browser C
13
History of Sockets
• In early 1980s, the Advanced Research Projects Agency (ARPA) funded a
group at UC Berkeley to transport TCP/IP software to the UNIX operating
system.
• As part of the project, the designers created an interface that applications
use for network communication.
• The interface used an abstraction known as a socket, and the API became
known as socket API.
• Many computer vendors adopted the Berkeley UNIX operating system,
and the socket interface became very popular.
• Subsequently, Microsoft chose the socket interface as the primary network
API for its operating systems, called WinSock.
— Old version: Windows Sockets 1.1
— Today’s version: Windows Sockets 2
•
•
http://www.sockets.com/winsock2.htm
The important header file: winsock2.h
• The socket interface has become a de facto standard throughout the
computer industry.
14
Specifying a Protocol Interface
• The designers at Berkeley wanted to accommodate
multiple sets of communication protocols.
— TCP/IP was not the only choice at that time!
• They allowed for multiple families of protocols, with
TCP/IP represented as a single family. E.g.,
— PF_INET or AF_INET (IPv4)
• Our focus
— PF_INET6 or AF_INET6 (IPv6)
— PF_UNIX or AF_UNIX (Unix domain protocols)
— PF_IPX or AF_IPX (IPX protocols)
15
Socket Descriptors
• To perform file I/O, we use a file descriptor.
• Similarly, to perform network I/O, we use a socket
descriptor:
— Each active socket is identified by its socket descriptor.
— The data type of a socket descriptor is SOCKET.
— Hack into the header file winsock2.h:
• typedef u_int SOCKET; /* u_int is defined as unsigned int */
— In UNIX systems, socket is just a special file, and socket
descriptors are kept in the file descriptor table.
— The Windows operating system keeps a separate table of
socket descriptors (named socket descriptor table, or
SDT) for each process.
16
How to Create a Socket?
• The socket API contains a function socket() that can
be called to create a socket. E.g.:
#include <winsock2.h>
…
SOCKET s;
…
s = socket(AF_INET, SOCK_DGRAM, 0) ;
The socket is not
usable yet. We need
to specify more
information before
using it for data
transmission.
17
Types of Sockets
• Under protocol family AF_INET
— Stream socket
• Uses TCP for connection-oriented reliable communication
• Identified by SOCK_STREAM
• s = socket(AF_INET, SOCK_STREAM, 0) ;
— Datagram socket
• Uses UDP for connectionless communication
• Identified by SOCK_DGRAM
• s = socket(AF_INET, SOCK_DGRAM, 0) ;
— RAW socket
• Uses IP directly
• Identified by SOCK_RAW
• Advanced topic. Not covered by COMP2330.
18
System Data Structures for Sockets
• When an application process calls socket(), the operating system allocates
a new data structure to hold the information needed for communication,
and fills in a new entry in the process’s socket descriptor table (SDT) with
a pointer to the data structure.
— A process may use multiple sockets at the same time. The socket descriptor
table is used to manage the sockets for this process.
— Different processes use different SDTs.
• The internal data structure for a socket contains many fields, but the
system leaves most of them unfilled. The application must make additional
procedure calls to fill in the socket data structure before the socket can be
used.
• The socket is used for data communication between two processes (which
may locate at different machines). So the socket data structure should at
least contain the address information, e.g., IP addresses, port numbers,
etc.
19
System Data Structures for Sockets
(Cont.)
Fig 5.2 from Comer.
Conceptual operating system (Windows) data structures after five calls to
socket() by a process. The system keeps a separate socket descriptor
table for each process; threads in the process share the table.
20
C Review: Structure
• C structures are collections of related variables under
one name.
struct employee {
};
typedef struct employee Employee;
char firstname[20];
Employee em;
char lastname[20];
Employee *pEm; /* pointer to structure */
int age;
em.salary = 23456; /* dot operator */
float salary;
pEm = &em; /* assign address of em to
pEm */
pEm->salary += 1000; /* struct pointer
operator */
21
memset() and memcpy()
memset(): set buffer to a specified character
void *memset(void *dest, int c, size_t count);
— dest : Pointer to destination.
— c : Character to set.
— count : Number of characters
memcpy(): copy characters between buffers
void *memcpy(void *dest, const void *src, size_t count);
— dest : New buffer.
— src : Buffer to copy from.
— count : Number of bytes to copy.
22
Addressing Issue
• How to identify a communication?
— Source IP Address, Source Port Number, Destination IP
Address, Destination Port Number
—TCP or UDP
• IPv4 address: 32-bit
• Port number: 16-bit
—http://www.iana.org/assignments/port-numbers
• Better to have a data structure that contains the
addressing information
—To simplify the socket APIs
—Number of function parameters can be decreased
23
Specifying an Endpoint Address
• When a socket is created, it doesn’t contain address
information of either local machine or the remote machine.
• Before an application uses a socket for sending/receiving data,
it must specify one or both of these addresses for the socket.
— This can simplify the APIs.
• TCP/IP define a communication endpoint to consist of an IP
address and a protocol port number.
— when you create the socket, you already specified whether this socket is
using TCP or UDP.
• Several data structures are involved to represent the endpoint
address
— A general structure: struct sockaddr
— A specific structure for IPv4: struct sockaddr_in
24
Generic Address Structure
• The socket system defines a generic endpoint address:
— (address family, endpoint address in that family)
— The purpose is to provide a common interface for different kinds of
protocol families
struct sockaddr {
u_short sa_family;
char sa_data[14];
};
/* address family */
/* up to 14 bytes of direct address */
• Unfortunately, not all address families define endpoints that fit
into the sockaddr structure!
• To keep program portable and maintainable, TCP/IP code
should not use the sockaddr structure in declarations.
• Instead, another structure sockaddr_in should be used to
represent a socket address in AF_INET family.
25
TCP/IP Endpoint Address
• TCP/IP (IPv4) endpoint address is defined as:
(AF_INET, 2-byte port number, 4-byte IP address, 8-byte zero).
struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
/* type of address, always AF_INET */
/* protocol port number */
/* IP address */
/* unused */
The IP address is stored in structure sin_addr with type struct in_addr:
struct in_addr {
union {
struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
struct { u_short s_w1,s_w2; } S_un_w;
u_long S_addr;
} S_un;
#define s_addr S_un.S_addr
…
};
The 32-bit IP address can be
explained as 4 unsigned
bytes, or 2 unsigned short, or
an unsigned long. By using a
union, you can manipulate
the IP address conveniently.
26
sockaddr vs. sockaddr_in
2 bytes
14 bytes
struct sockaddr
struct sockaddr_in
sa_family
sin_family
2 bytes
sin_port
2 bytes
sin_addr
4 bytes
sin_zero
8 bytes
sa_data
A pointer to a struct sockaddr_in can be cast to a pointer to a struct sockaddr and vice-versa.
27
An Example
• To specify an endpoint address 158.182.9.1:5678
#include <winsock2.h>
…
There are several ways to specify
an IP address:
struct sockaddr_in addr;
• Use a string – Good!
…
• “158.182.9.1”
• Use an integer – Bad!
• 2662729985
addr.sin_family = AF_INET;
addr.sin_port = htons(5678);
addr.sin_addr.s_addr = htonl(2662729985);
• Use DNS service – Good!
Remark: 2662729985 = 10011110101101100000100100000001
1
182
158
9
28
Byte Ordering
• Byte Ordering:
• Memory is organized in bytes.
• E.g, a 16-bit integer takes 2 consecutive bytes; a 32-bit integer
takes 4 consecutive bytes.
• Different machines use different host bye orderings:
• little-endian: least significant byte located at lower memory
• E.g., Intel 80x86
• big-endian: least significant byte located at higher memory
• E.g., Motorola 68000
• These machines may communicate with one another over the
network, and they may have different understandings on the same
data.
• Not a problem for data type char
29
Chaos of Byte Order
Big-Endian
Computer
Send out an integer
169283078
Little-Endian
Computer
Receive an integer
68032266!
30
Solution: Network Byte Order
• Let’s have some regulation!
— Network byte order is defined as big-endian byte order
— Integers should be sent out in network byte order
• The members sin_port and sin_addr in struct sockaddr_in
should be in network byte order
— sin_port: TCP or UDP port number, put into the TCP/UDP header
— sin_addr: IP address, put into the IP header
• The member sin_family will not be sent out to the network.
So it is not necessary to be in network byte order.
• If your application needs to transfer integers between two
machines, you should transfer them into network byte order.
— You don’t know the type of CPU that executes your program!
31
Network Byte Order
• When sending out an integer
—Transfer it into network byte order by:
—u_short htons (u_short host_short);
—u_long htonl (u_long host_long);
• After receiving an integer
—Transfer it into (local) host byte order by:
—u_short ntohs (u_short network_short);
—u_long ntohl (u_long network_long);
• Remark:
—u_short: unsigned 16-bit integer
—u_long: unsigned 32-bit integer
h: host
n: network
s: short
l: long
h-to-n-s
h-to-n-l
n-to-h-s
n-to-h-l
32
WinSock API
Function Name
Meaning
WSAStartup
Initialize the socket library (Windows only)
WSACleanup
Terminate use of socket library (Windows only)
WSAGetLastError
Retrieve the specific error code following an unsuccessful socket
function call (Windows only)
socket
Create a socket used for network communication
connect
Connect to a remote peer (client)
closesocket
Terminate communication and remove the socket
bind
Specify a local IP address and protocol port for a socket
listen
Place the socket in passive mode and set the number of incoming TCP
connections the system will enqueue (server)
accept
Accept the next incoming connection (server)
33
WinSock API
Function Name
Meaning
recv
Acquire incoming data from a stream connection or the next incoming
message (mainly for TCP)
recvfrom
Receive the next incoming datagram and record its source endpoint
address (UDP)
send
Send outgoing data or a message (mainly for TCP)
sendto
Send an outgoing datagram to a specified endpoint address (UDP)
select
Wait until the first of a specified set of sockets becomes ready for I/O
shutdown
Terminate a TCP connection in one or both directions
inet_addr
Convert IP address in dotted decimal form to internal binary form
inet_ntoa
Convert IP address from internal binary form to a text string
gethostbyname
Map a host name to an IP address
34
A TCP Client-Server Example
CLIENT SIDE
SERVER SIDE
WSAStartup()
WSAStartup()
socket()
socket()
bind()
listen()
connect()
accept()
send()
recv()
recv()
send()
closesocket()
closesocket()
WSACleanup()
WSACleanup()
Remark:
The server runs forever. It
waits for a new connection
on the well-known port,
accepts the connection,
interacts with the client, and
then closes the connection.
35
A UDP Client-Server Example
UDP Server
UDP Client
WSAStartup()
WSAStartup()
socket()
socket()
sendto()
bind()
data (request)
recvfrom()
process request
recvfrom()
data (reply)
sendto()
closesocket()
closesocket()
WSACleanup()
WSACleanup()
36
Comparison Between TCP and UDP
• Common function calls
—WSAStartup(), WSACleanup()
—socket(), closesocket()
—bind()
• Differences
—TCP is connection-oriented, UDP is connectionless
• TCP applications use listen(), accept(), connect() to setup TCP
connections
—Data transfer
• TCP applications use send() and recv()
• UDP applications use sendto() and recvfrom()
37
WSAStartup()
Programs using WinSock must call WSAStartup() before using sockets. It is
needed because the operating system uses dynamically linked libraries (DLLs).
int WSAStartup ( WORD wVersionRequested, LPWSADATA lpWSAData );
• wVersionRequested : The highest version of Windows Sockets support that the caller can use.
The high order byte specifies the minor version (revision) number; the low-order byte specifies
the major version number.
• lpWSAData : A pointer to the WSADATA data structure that is to receive details of the
Windows Sockets implementation.
WSAStartup() returns zero if successful.
Example code:
WSADATA wsadata;
int err;
err = WSAStartup(MAKEWORD(2,2), &wsadata);
if (err != 0) return;
38
WSACleanup()
• Once an application finishes using and closing
sockets, it calls WSACleanup() to deallocate all data
structures and socket bindings.
• A program usually calls WSACleanup() only when it
is completely finished and ready to exit.
int WSACleanup(void);
The return value is zero if the operation was successful. Otherwise, the value SOCKET_ERROR
is returned.
39
WSAGetLastError()
• An application calls the WSAGetLastError function to retrieve
the specific error code following an unsuccessful socket
function call.
• An application should call WSAGetLastError immediately
after a socket function returns an error indication.
— So that you can know what the problem is.
• Windows Sockets Error Codes
— http://msdn.microsoft.com/en-us/library/ms740668.aspx
int WSAGetLastError(void);
The return value indicates the error code for this thread's last Windows Sockets operation that
failed.
40
socket()
The Windows Sockets socket() function creates a socket.
SOCKET socket ( int af, int type, int protocol );
• af: An address family specification.
• type: A type specification for the new socket. The following are the only two type
specifications supported for Windows Sockets 1.1: SOCK_STREAM and SOCK_DGRAM.
In Windows Sockets 2, some new socket types are introduced.
• protocol: A particular protocol to be used with the socket that is specific to the indicated
address family. Remark: we usually set it as 0.
If no error occurs, socket() returns a descriptor referencing the new socket. Otherwise, a value of
INVALID_SOCKET is returned.
Example code:
SOCKET s;
s = socket(AF_INET, SOCK_STREAM, 0);
if (s == INVALID_SOCKET) {
printf(“Error code: %d\n”, WSAGetLastError());
return;
}
41
closesocket()
•
•
•
Once a client or server finishes using a socket, it calls closesocket() to
deallocate it.
If only one process is using the socket, closesocket() immediately terminates
the connection and deallocates the socket.
If several processes share a socket, closesocket() decrements a reference count
and deallocates the socket when the reference count reaches zero.
int closesocket (SOCKET s);
If no error occurs, closesocket() returns zero. Otherwise, a value of SOCKET_ERROR is
returned.
42
Assigning Endpoint Address
At the server side:
At the client side:
#define S_PORT 13
#define S_PORT 13
struct sockaddr_in servaddr;
struct sockaddr_in servaddr;
…
…
memset(&servaddr, 0, sizeof(servaddr));
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(S_PORT);
servaddr.sin_port = htons(S_PORT);
servaddr.sin_addr.s_addr = inet_addr(argv[1]);
Remark:
Remark:
INADDR_ANY represents a wildcard address that
matches any of the computer’s IP address.
inet_addr() takes an ASCII string that contains a
dotted decimal address and returns the equivalent
IP address in binary.
In winsock2.h:
#define INADDR_ANY (u_long)0x00000000
The server doesn’t know who will connect to it.
It needs to define the local port number only.
argv[1] represents the first argument to the
command.
The client must provide the IP address
and port number of the server.
43
How to Get the Server Address?
• The client software needs to know the server’s
address.
• You can:
—Include the address into the source code
• Not flexible. If the server’s address is changed, you have to
recompile your source code.
—Require the user to identify the server when invoking the
program
• the most popular way
44
inet_addr(): Parsing an Address
• The arguments are stored in character strings
• E.g., when user input an IP address “128.10.2.3”, your
program usually receives just a string. You need to transfer
this string into an IP address data structure.
unsigned long inet_addr ( const char * cp );
If successful, inet_addr() returns an unsigned long that contains the IPv4 address in binary
form using network byte order. Otherwise, inet_addr() returns INADDR_NONE to indicate
that the argument does not contain a valid dotted decimal address.
Example code:
void main (int argc, char * argv[]) {
struct sockaddr_in servaddr;
…
servaddr.sin_addr.s_addr = inet_addr(argv[1]);
}
45
inet_ntoa(): Output an IP Address
• char * inet_ntoa(struct in_addr in);
• The inet_ntoa() function takes an Internet address
structure specified by the in parameter and returns
an ASCII string representing the address in dot
notation as in "a.b.c.d''.
• Good for output!
Example code:
char *a;
struct sockaddr_in servaddr;
…
a = inet_ntoa(servaddr.sin_addr);
printf(“address is : %s\n”, a);
46
Looking Up a Domain Name
• Internet hosts can be identified by IP address or hostnames.
• The Domain Name Service (DNS) provides mapping
between hostname and IP address
— E.g.:
• www.hkbu.edu.hk  158.182.4.1
• www.google.com  66.249.89.104
• How can we use DNS service?
— To enjoy DNS services, you must keep the IP address of a default DNS
server (or more backups), configured by hand or by DHCP.
• Check this out by command “ipconfig /all”.
— Every time you need to map a domain name into its corresponding IP
address, you call the function gethostbyname().
• It will trigger the OS to contact the DNS server to obtain the IP address.
47
gethostbyname()
•
•
Sometimes one domain name are mapped to a list of IP addresses (e.g., for a cluster
server).
Instead of returning a single IP address, it will return a complicated data structure
“hostent” which can store a list of IP addresses.
struct hostent {
char *
h_name;
/* official host name */
char **
h_aliases;
/* other aliases */
short
h_addrtype;
/* address type */
short
h_length;
/* length of each address in bytes */
char **
h_addr_list;
/* list of addresses */
#define h_addr h_addr_list[0]
};
struct hostent * gethostbyname( const char* name);
Example code:
char* server = “www.comp.hkbu.edu.hk”;
1. It will return a NULL pointer
struct hostent *h;
if error occurs.
…
2. The returned IP address is in
network byte order.
if ( h = gethostbyname(server) )
memcpy(&servaddr.sin_addr, h->h_addr, h->h_length);
48
getservbyname()
Most client programs must look up the protocol port for the specific service they wish to
invoke. To do so, the client invokes library function getservbyname() which takes two
parameters: (1) a string that specifies the desired service; (2) a string that specifies the
transport protocol being used (i.e., tcp or udp).
struct servent {
char * s_name;
char ** s_aliases;
short s_port;
char * s_proto;
};
/* official service name */
/* other aliases */
/* port for this service */
/* protocol to use */
struct servent getservbyname ( const char * name, const char * proto );
Example code:
struct servent *sptr;
if ( sptr = getservbyname (“smtp”, “tcp”) ) {
/* port number is now in sptr->s_port */
} else {
/* error occurred – handle it */
}
Another similar library
function is getprotobyname().
Check it out by yourself.
49
bind()
• When a socket is first created, it has no associated endpoint addresses.
• Function bind() can specify the local endpoint address for a socket.
— Usually, a server calls bind() to specify the well-known port at which they will
await connections.
— A client can skip bind() and let OS to decide.
int bind(SOCKET s, const struct sockaddr * addr, int addrlen);
• s: the socket descriptor
• addr: a pointer to the address assigned to the socket
• addrlen: the size (in bytes) of the real address structure
If no error occurs, bind() returns 0. Otherwise, it returns SOCKET_ERROR.
Example code:
SOCKET s;
struct sockaddr_in servaddr;
/* fill in the fields of servaddr */
…
if ( bind(s, (struct sockaddr*)&servaddr, sizeof(servaddr)) == SOCKET_ERROR ) {
/* error handling */
}
50
Choosing Local Address
• Local port number
— A server operates at a well-known protocol port address, which all
clients must know.
— In general, the client does not care which port it uses as long as the port
has no conflict and the port is not assigned to a well-known service.
— For TCP connection, the local port is assigned by the OS during the
call of connect() function.
• Local IP address
— It’s trivial for most machines that has only one IP address.
— But for a machine with multiple IP addresses, it could be more
complicated.
• TCP client software usually leaves the local endpoint address
unfilled, and allows TCP/IP module to select the correct local
IP address and an unused local port number automatically.
51
Iterative TCP Server Algorithm
1.
Create a socket and bind to the well-known address for the service being
offered.
•
2.
Place the socket in passive mode, making it ready for use by a server.
•
3.
accept()
Repeatedly receive a request from the client, formulate a response, and
send a reply back to the client according to the application protocol.
•
5.
listen()
Accept the next connection request from the socket, and obtain a new
socket for the connection.
•
4.
socket() and bind()
recv() and send()
When finished with a particular client, close the connection and return to
step 3 to accept a new connection.
•
closesocket()
52
listen()
• TCP server calls listen() to place a socket in passive mode and makes it
ready to accept incoming connections.
— A socket in passive mode is used for acceptance of TCP connection request, not
for data transfer.
• To handle multiple clients for the server, listen() tells the operating system
to queue the connection requests for the server’s socket.
int listen(SOCKET s, int backlog);
• s: the socket descriptor
• backlog: the maximum length of the queue of pending connections
If no error occurs, listen() returns 0. Otherwise, it returns SOCKET_ERROR.
Example code:
SOCKET listenfd, connfd;
struct sockaddr_in servaddr;
…
bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
if ( listen(listenfd, 10) == SOCKET_ERROR) {
/* error handling */
}
53
accept()
•
•
After the server calls listen(), the server can then call accept() to extract the next
incoming connection request from the listening queue.
Function accept() creates a new socket for each new successful connection request,
and returns the descriptor of the new socket to its caller. This new socket is used to
transfer data.
SOCKET accept(SOCKET s, struct sockaddr * addr, int *addrlen);
• s: the socket descriptor
• addr: an optional pointer to a buffer that receives the client’s address
• addrlen: an optional pointer to an integer that contains the length of the client’s address
structure
Return value:
If no error occurs, accept() returns the socket descriptor for the newly accepted
socket.
Otherwise, a value of INVALID_SOCKET is returned .
54
accept()
Example code:
SOCKET listenfd, connfd;
struct sockaddr_in cliaddr;
int clilen;
…
listenfd = socket(AF_INET, SOCK_STREAM, 0);
…
bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
listen(listenfd, 10);
connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
Remark:
listenfd is used to accept client connection request.
connfd is used for sending/receiving data.
55
Server: Two Kinds of Sockets
Server Process
Client Process
Listening
socket
socket
Server Process
Client Process
data
data
data
socket
A new socket
returned by
accept()
56
Server: Two Kinds of Sockets
Browser A
Web Server
Browser B
socket
socket
Remark:
socket
Browser C
A single listening socket is
used by the server to accept
incoming connection
requests.
57
TCP Client Algorithm
1.
2.
Find the IP address and protocol port number of the server with which
communication is desired;
Allocate a socket;
•
3.
Specify that the connection needs an arbitrary, unused protocol port on
the local machine, and allow TCP to choose one;
•
4.
connect()
Communicate with the server using the application-level protocol;
•
6.
A side-effect of connect()
Connect the socket to the server;
•
5.
socket()
send() and recv()
Close the connection.
•
closesocket()
58
connect()
• A client calls connect() to establish an active
connection to a remote server.
int connect (SOCKET s, struct sockaddr * addr, int addrlen);
• s: the socket descriptor
• addr: a pointer to the server’s address
• addrlen: the length of the server’s address structure
If no error occurs, connect()
returns 0. Otherwise, it returns
SOCKET_ERROR.
Example code:
Remark:
SOCKET s;
servaddr is declared as type struct
struct sockaddr_in servaddr;
sockaddr_in.
…
It is cast into type struct sockaddr
s = socket(AF_INET, SOCK_STREAM, 0);
when calling connect().
/* fill in the structure servaddr */
…
if ( connect(s, (struct sockaddr *)&servaddr, sizeof(servaddr)) == SOCKET_ERROR ) {
/* error handling */
}
59
…
TCP Communications
• When TCP is used, TCP module uses a sending buffer and a
receiving buffer for reliable data transmission.
— These buffers are inside the OS kernel and different from your
application memory buffer!
• For sending out data, send() is used.
— Usually when send() returns, all the data have been put into the send
buffer. We can assume that these data will be successfully delivered
eventually.
• For receiving data, recv() is used.
— But when recv() returns, the number of received bytes could be
different from what you expect (i.e., different from what the other side
has sent).
— You must be careful when using recv(). You need to check how many
bytes of data have been actually received and then decide what to do
next.
60
TCP: Sending Data
• For a TCP connection (SOCK_STREAM), both client and server call
send() to send data and recv() to receive data.
int send(SOCKET s, const char * buf, int len, int flags);
• s: the socket descriptor
• buf: a pointer to the message to be sent out
• len: the length of the message in bytes
If no error occurs, send() returns
the total number of bytes sent.
Otherwise, a value of
SOCKET_ERROR is returned.
• flags: can be 0 or MSG_OOB or MSG_DONTROUTE
Remark:
Each TCP socket has a send buffer in the OS. When we call send(), the OS copies all the
data from the application buffer to the socket send buffer. And the TCP module in the OS
kernel will handle the data transfer on the background.
1. If the send buffer has enough room, send() will return just after the data copying.
2. If the send buffer has no enough room, send() will block itself until all the data are
copied into the send buffer.
61
TCP: Receiving Data
int recv(SOCKET s, char * buff, int len, int flags);
• s: the socket descriptor
• buf: a pointer to the buffer to receive incoming data
• len: the size of the buffer
• flags: can be 0 or MSG_OOB or MSG_PEEK
Each TCP socket also has a receive buffer in the OS to hold received data until it is read by the
application (by calling the recv() function). So before calling recv(), an application buffer must be
allocated by the user to store the incoming data. Function recv() will copy the incoming data from
the OS kernel to the application buffer.
1. If no data has arrived, recv() will block until data arrives;
2. If the incoming data can fit into the application buffer, recv() extracts all the data and returns
the number of bytes received;
3. If the incoming data cannot fit into the application buffer, recv() only extracts enough to fill the
buffer. It may be necessary to call recv() several times in order to receive the entire message.
4. If the other side closed the socket, recv() will return 0.
62
Challenges
• TCP allows reliable data transmission between two
processes
—Data are regarded as byte stream.
—There is no data boundary.
• Problems
—The receiver doesn’t know how much data to receive.
—The number of bytes returned by recv() cannot be known
in advance.
• Multiple calls of recv() is a common practice. But you don’t know
how many times to call recv()!
• Solutions?
63
Example 1: If Length is Known
In this example, we assume the sender will send 20000 bytes to the receiver.
But the receiving application may receive data in small chunks.
/* receiver code */
#define BLEN 20000
char buf[BLEN];
int n, c=0;
buf
&buf[n]
n += c
for (n = 0; n < BLEN; n += c) {
c = recv(s, &buf[n], BLEN-n, 0);
}
Question: in reality, how can the client know the length of the
incoming data, i.e., 20000 bytes?
64
Example 2:
Connection Closed by Your Peer
In this example, we assume the sender will send some bytes (no more than 20000) to
the receiver and then close the socket.
The receiver will keep on receiving data until the recv() returns 0.
/* receiver code */
#define BLEN 20000
char buf[BLEN];
char *bptr;
int n, buflen;
bptr = buf;
buflen = BLEN;
n = recv(s, bptr, buflen, 0);
while ((n != SOCKET_ERROR) && (n != 0)) {
bptr += n;
buflen -= n;
n = recv(s, bptr, buflen, 0);
}
buf
n
bptr
bptr
65
Example 3: A General Solution Data Encapsulation
• The sender sends length + data to the receiver.
— Usually it is enough to use a 32-bit integer for length
— Remember to use Network Byte Order for the integer!
• The receiver extracts length, then allocates memory, then
receives the data (see Example 1).
/* sender code */
SOCKET sock;
int len, m;
char *buf;
…
len = 20000;
buf = malloc(len);
… /* fill the buf by your data */
m = htonl(len);
send(sock, &m, sizeof(m), 0);
send(sock, buf, len, 0);
…
/* receiver code */
SOCKET sock;
int i, c, n, len;
char *buf, *ptr;
…
ptr = &n; len = sizeof(n);
for (i = 0; i < len; i += c)
c = recv(sock, &ptr[i], len-i, 0);
len = ntohl(n);
buf = malloc(len);
for (i = 0; i < len; i += c)
c = recv(sock, &buf[i], len-i, 0);
66
UDP Client Algorithm
1.
2.
3.
4.
5.
Find the IP address and protocol port number of the server
with which communication is desired;
Allocate a socket;
Specify that the communication needs an arbitrary, unused
protocol port on the local machine, and allow UDP to choose
one;
Specify the server to which messages must be sent;
Communicate with the server using the application-level
protocol;
•
6.
This usually involves sending requests and awaiting replies
Close the socket.
67
UDP: Sending / Receiving Data
• For connectionless service, i.e., UDP (SOCK_DGRAM), sendto() and
recvfrom() are normally used for data transfer.
int sendto(SOCKET s, const char * buff, int buflen, int flags, const struct sockaddr * to, int tolen)
sendto() requires the destination endpoint address as an argument. Why send() doesn’t?
sendto() returns the number of bytes sent if successful, and SOCKET_ERROR to indicate that an
error has occurred.
int recvfrom(SOCKET s, char * buff, int buflen, int flags, struct sockaddr * from, int * fromlen)
recvfrom() extracts the next message that arrives at a socket and records the sender’s address.
recvfrom() returns the number of bytes in the message if successful, and SOCKET_ERROR to
indicate that an error has occurred.
The receiver doesn’t know who will send him data. Any machine can send data to this receiver if
it knows the receiver’s IP and UDP port.
Please study the example codes on Page 7 and 8.
68
“Connected” UDP
• UDP is connectionless.
— When call sendto() and recvfrom(), the peer’s address is included or
returned as a parameter.
— An unconnected UDP socket can receive packets from any machine.
• Somehow, there is a “connected” UDP socket
— You can call connect() to store the destination’s address in the OS
kernel at the beginning
— We can no longer specify the destination’s address
— We can call send() to send a message and recv() to receive a response.
Each call to recv() returns one complete message.
— Connected UDP socket is still UDP. The only difference with
unconnected UDP socket is the including of destination address
information. With this information, the OS will help you to filter out
the messages from unknown peers.
69
More about UDP Programming
• Reliability issue
— A client must implement reliability through timeout and
retransmission, if reliability is desired.
— Even if your application doesn’t require reliability, it is important to
use timeout control because recvfrom() will block forever if the
expected incoming packet is lost.
• Flow control issue
— UDP module has no flow control (but TCP has).
— A high performance PC can send out tens of thousands of packets per
second with a 100Mbps Ethernet. But a very slow PC may be
swallowed by so huge UDP traffic! If the slow PC’s CPU is too busy,
the UDP receive buffer will be accumulated to full and the new
incoming UDP packets will be dropped.
70
More References
• Learn by practicing!
— Some example codes are available on the course web site.
— Use WireShark to learn basic socket programming debugging skills.
— Start with some toy programs.
— Finish the course project individually.
• References:
— Douglas E. Comer and David L. Stevens, Internetworking with
TCP/IP, Volume III: client-server programming and applications, 1997,
Prentice-Hall.
— W. Richard Stevens, Bill Fenner, and Andrew M. Rudoff, UNIX
Network Programming, Volume I: The Sockets Networking API, 3rd
Edition, 2004, Addison-Wesley.
— Winsock Programming FAQ: http://www.tangentsoft.net/wskfaq/
71