Socket Programming

advertisement
Part 1
IPv6 ready
C/C++ Language
1
Getting Started…
 WinSock Functions
 Predefined constants and error codes
 Special Structures, Unions and data types
suited for socket programming
 Correct order of function calls to synchronize
Server and Client applications
2
Socket Programming
Goal: learn how to build client/server application that
communicate using sockets
Socket API
 introduced in BSD4.1 UNIX, 1981
 explicitly created, used, released by
applications
 uses client/server paradigm
 two types of transport service via
socket API:
 unreliable datagram
 reliable, byte stream-oriented
 WinSock 2 - to provide a
protocol-independent transport
interface that is fully capable of
supporting emerging networking
capabilities including real-time
multimedia communications
socket
a host-local, applicationcreated/owned,
OS-controlled interface (a
"door") into which
application process can
both send and
receive messages to/from
another (remote or
local) application process
3
4
Socket Programming using TCP
Socket: a door between application process and endend-transport protocol (UDP or TCP)
TCP service: reliable transfer of bytes from one process
to another
controlled by
application
developer
controlled by
operating
system
process
process
socket
TCP with
buffers,
variables
client or
server
Internet
socket
TCP with
buffers,
variables
client or
server
controlled by
application
developer
controlled by
operating
system
5
Socket Programming with TCP
Client must contact server
 server process must first be
running
 server must have created
socket (“door”) that
welcomes client’s contact
 When contacted by client,
server TCP creates new
socket for server process to
communicate with client
 allows server to talk with
multiple clients
Server socket
“Client knocking on the door”
Application Viewpoint
Client contacts server by:
creating client-local TCP socket
specifying IP address, port
number of server process
TCP provides reliable, in-order
transfer of bytes ("pipe")
between client and server
6
Socket Programming with TCP
Example of a client-server application:
 Client reads line from standard input
 Client sends to server via socket
 Server reads line from socket
 Server counts the number of bytes contained in the
line and sends it back to client
 Client reads and prints the message stating how
many bytes it has sent originally
7
Client/server socket interaction: TCP
Server (running on hostid)
Client
create socket,
port=x, for
incoming request:
welcomeSocket =
socket()
wait for incoming
connection request
connectionSocket =
accept()
read request from
connectionSocket
write reply to
connectionSocket
close
connectionSocket
TCP
connection setup
create socket,
connect to hostid, port=x
clientSocket =
socket()
send request using
clientSocket
read reply from
clientSocket
close
clientSocket
8
Application 2-8
Proper Ordering of Send and Recv
socket
socket
bind
listen
connect
/* communicate with server*/
loop "forever"
loop until done
{
{
accept /* by creating newsocket */
send
/* communicate with client*/
loop until done
{
receive
}
closesocket(socket)
receive
send
}
closesocket(newsocket)
}
9
Simple Client-Server
TCP Control Socket
C
Listening
Socket
S
Temporary TCP Socket for Client
Server
 In TCP, the Server should be running already prior to a
Client connecting to it
10
Stream jargon
 stream is a sequence of
output
stream
inFromServer
Process
Client
process
outToServer
characters that flow into
or out of a process.
 input stream is attached
to some input source for
the process, e.g.,
keyboard or socket.
 output stream is
attached to an output
source, e.g., monitor or
socket.
input
stream
monitor
inFromUser
keyboard
input
stream
client
TCP
clientSocket
socket
to netw ork
TCP
socket
from netw ork
11
Application 2-11
12
Client/Server Socket Interaction: UDP
1. No handshaking - has no connection establishment
2. No streams are attached to the sockets.
3. Sender creates packets of bytes with IP destination
address Port number.
4. Receiving host must unravel each packet received to
obtain the packet’s information bytes.
UDP (User Datagram Protocol)
–No connection state at servers
- less packet overhead than TCP
- light error-checking (checksum)
- server doesn’t use the listen() function
- server doesn’t use the accept() function
13
Client/server socket interaction: UDP
Server (running on hostid)
create socket,
port= x.
serverSocket =
Socket()
read datagram from
serverSocket
write reply to
serverSocket
specifying
client address,
port number
Client
create socket,
clientSocket =
Socket()
Create datagram with server
(hostid, port=x), send datagram via
clientSocket
read datagram from
clientSocket
close
clientSocket
14
Application 2-14
Some utility: Netstat
Netstat -a
Active Connections
Proto
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
TCP
Local Address
Foreign Address
State
IT027049:http
IT027049.massey.ac.nz:0 LISTENING
IT027049:epmap
IT027049.massey.ac.nz:0 LISTENING
IT027049:https
IT027049.massey.ac.nz:0 LISTENING
IT027049:microsoft-ds IT027049.massey.ac.nz:0 LISTENING
IT027049:1025
IT027049.massey.ac.nz:0 LISTENING
IT027049:1179
IT027049.massey.ac.nz:0 LISTENING
IT027049:1181
IT027049.massey.ac.nz:0 LISTENING
IT027049:1300
IT027049.massey.ac.nz:0 LISTENING
IT027049:1318
IT027049.massey.ac.nz:0 LISTENING
IT027049:1786
IT027049.massey.ac.nz:0 LISTENING
IT027049:1787
IT027049.massey.ac.nz:0 LISTENING
IT027049:1790
IT027049.massey.ac.nz:0 LISTENING
IT027049:1791
IT027049.massey.ac.nz:0 LISTENING
IT027049:5000
IT027049.massey.ac.nz:0 LISTENING
IT027049:13450
IT027049.massey.ac.nz:0 LISTENING
IT027049:netbios-ssn IT027049.massey.ac.nz:0 LISTENING
IT027049:1082
IT027049.massey.ac.nz:0 LISTENING
IT027049:1179
its-xchg4.massey.ac.nz:1165 ESTABLISHED
IT027049:1181
its-dc2.massey.ac.nz:1025 ESTABLISHED
IT027049:1318
hnt-up-dhcp-494.wharton.upenn.edu:62686 ESTABLISHED
IT027049:1456
IT027049.massey.ac.nz:0 LISTENING
IT027049:1456
alb-file2.massey.ac.nz:netbios-ssn ESTABLISHED
IT027049:1467
IT027049.massey.ac.nz:0 LISTENING
IT027049:1467
itsa-campus1.massey.ac.nz:netbios-ssn ESTABLISHED
IT027049:1786
d226-94-36.home.cgocable.net:7091 ESTABLISHED
Displays all active TCP
connections and the TCP and
UDP ports on which the
computer is listening
15
TCP
TCP
TCP
TCP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
UDP
IT027049:1787
IT027049:1790
IT027049:1791
IT027049:8947
pcp0011009611pcs.detrtc01.mi.comcast.net:21848 ESTABLISHED
balticom-132-227.balticom.lv:63567 ESTABLISHED
24-29-117-20.nyc.rr.com:1236 ESTABLISHED
IT027049.massey.ac.nz:0 LISTENING
IT027049:microsoft-ds *:*
IT027049:isakmp
*:*
IT027049:1026
*:*
IT027049:1027
*:*
IT027049:1028
*:*
IT027049:1046
*:*
IT027049:1088
*:*
IT027049:1177
*:*
IT027049:13450
*:*
IT027049:38037
*:*
IT027049:ntp
*:*
IT027049:1187
*:*
IT027049:1459
*:*
IT027049:1718
*:*
IT027049:1900
*:*
IT027049:ntp
*:*
IT027049:netbios-ns *:*
IT027049:netbios-dgm *:*
IT027049:1900
*:*
IT027049:8760
*:*
IT027049:62493
*:*
16
Testing the Client-Server Codes
 Run ServerWindows.c
 Compile ClientWindows.c, look for the
executable.
 Run ClientWindows.c from the command
prompt to connect to the server:
 ClientWindows
localhost 1234
 Alternatively, use IpConfig to find out what your IP
address is: (e.g. 130.123.123.111), then connect
to the server using:
• ClientWindows 130.123.123.111 1234
17
IPv6 ready
18
Winsock application startup
Headers required
//Ws2_32.lib
#define _WIN32_WINNT 0x501 //to recognise getaddrinfo()
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
//#pragma comment (lib, "Ws2_32.lib")
In Windows 7,
C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib\x64\Ws2_32.lib
C:\Windows\System32\WS2_32.dll
19
Winsock application startup
makefile
server.exe
: server.o
g++ -Wl,-s -o server.exe server.o -lws2_32
Name of
your
program
server.o
: server.cpp
g++ -c -fpermissive -fconserve-space server.cpp
If compiling using Scite,
Select Tools, then Build (or Ctrl+F7)
20
Winsock application startup
Use a macro to define the preferred version number of the socket
DLL.
Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h
The high-order byte specifies the minor version number;
the low-order byte specifies the major version number.
Ver.2.2
#define WSVERS MAKEWORD(2,2)
21
Winsock application startup
Initialise Winsock DLL
//Create a WSADATA object called wsadata.
WSADATA wsadata;
// Initialize the use of the Windows Sockets DLL before making other
// Winsock functions calls.
// This also makes certain that Winsock is supported on the system.
int err;
err = WSAStartup(WSVERS, &wsadata);
if (err != 0) {
WSACleanup();
// Tell the user that we could not find a usable WinsockDLL
printf("WSAStartup failed with error: %d\n", err);
}
22
Winsock application startup
Verify the Winsock DLL version
//**************************************************************************************
/* Confirm that the WinSock DLL supports 2.2.
*/
/* Note that if the DLL supports versions greater
*/
/* than 2.2 in addition to 2.2, it will still return 2.2 in wVersion since that is
the version we requested.
*/
//**************************************************************************************
if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 2) {
/* Tell the user that we could not find a usable */
/* WinSock DLL.
*/
printf("Could not find a usable version of Winsock.dll\n");
WSACleanup();
exit(1);
}
else{
printf("=================== SERVER ==================\n");
printf("The Winsock 2.2 dll was found okay\n");
23
}
Winsock application startup
Set the socket address structure.
#define DEFAULT_PORT "1234"
struct addrinfo *result = NULL, *ptr = NULL, hints;
int iResult;
ZeroMemory(&hints, sizeof (hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the local address and port to be used by the server
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
exit(1);
}
See sample code for a more elaborate approach.
24
Winsock application startup
Create a socket for listening.
SOCKET s;
s = INVALID_SOCKET; //socket for listening
// Create a SOCKET for the server to listen for client connections
s = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
//check for errors in socket allocation
if (s == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
exit(1);
}
25
Winsock application startup
Bind the socket to the Server’s IP address and port number
int iResult = bind(s, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(s);
WSACleanup();
exit(1);
}
freeaddrinfo(result); //free the memory allocated by the getaddrinfo
//function for the server's address, as it is
//no longer needed
26
Winsock application startup
Set the listen socket in motion.
if (listen( s, SOMAXCONN ) == SOCKET_ERROR ) {
printf( "Listen failed with error: %ld\n", WSAGetLastError() );
closesocket(s);
WSACleanup();
exit(1);
}
A special constant that allows for a
maximum reasonable number of
pending connections in the queue
27
Winsock application startup
Accept a connecting client.
SOCKET ns;
int addrlen = sizeof(remoteaddr);
ns = INVALID_SOCKET;
//Accept a client socket
//ns = accept(s, NULL, NULL);
ns = accept(s,(struct sockaddr *)(&remoteaddr),&addrlen);
if (ns == INVALID_SOCKET) {
printf("accept failed: %d\n", WSAGetLastError());
closesocket(s);
Once an incoming client is
WSACleanup();
detected, a new socket is created to
return 1;
accept the client for connection.
} else {
printf("A CLIENT has been accepted.\n");
printf("\nConnected to CLIENT with IP address: %s, at port: %s\n",
inet_ntoa(remoteaddr.sin_addr),portNum);
}
28
Winsock application startup
Communicate with the client (receive, process, send message).
while (1) {
n = 0;
Remove
while (1) {
bytes = recv(ns, &receive_buffer[n], 1, 0);
delimeters
if ((bytes == SOCKET_ERROR) || (bytes == 0)) break;
if (receive_buffer[n] == '\n') { /*end on a LF*/
receive_buffer [n] = '\0';
break;
}
if (receive_buffer[n] != '\r') n++; /*ignore CRs*/
}
if ((bytes == SOCKET_ERROR) || (bytes == 0)) break;
sprintf(send_buffer, "client typed '%s' with %d bytes of information\r\n", receive_buffer, n);
printf("\nThe client sent: %s\n", receive_buffer);
//********************************************************************
bytes = send(ns, send_buffer, strlen(send_buffer), 0);
if (bytes == SOCKET_ERROR) break;
}
29
Winsock application startup
Shutdown connection with client
int iResult = shutdown(ns, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ns);
shutdown the send half of the
WSACleanup();
connection since no more data
exit(1);
will be sent
}
closesocket(ns);
printf("\ndisconnected from %s\n",inet_ntoa(remoteaddr.sin_addr));
30
Winsock application startup
Shutdown the server
closesocket(s);
WSACleanup();
/* call WSACleanup when done using the Winsock dll */
To release the allocated
resources.
31
32
Winsock application startup
#include <winsock.h>
#define WSVERS MAKEWORD(2, 2)
WSADATA wsadata;
C:\Windows\System32\WS2_32.dll
if (WSAStartup(WSVERS, &wsadata) != 0) {
printf(“WSAStartup failed\n”);
WSACleanup();
exit(1);
}
•The WSADATA structure contains information about the Windows Sockets
implementation.
• When it has completed the use of WinSock, the application must call
WSACleanup() to unregister itself from a WinSock implementation and
allow the implementation to free any resources allocated on behalf of the
application.
Windows data types:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx
33
Programming: Data Structures
 sockaddr_in
struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
sockaddr_in contains 4 fields.
 sin_port - specifies a Port number
 sin_addr - a 32-bit IP address
 sin_zero - should be set to zeros!
 sin_family - specify TCP/IP
34
Programming: Data Structures
Internet address structure
struct in_addr {
union {
struct { u_char s_b1, s_b2, s_b3, s_b4; } S_un_b; //byte representation
struct { u_short s_w1, s_w2; } S_un_w; //word representation
u_long S_addr; //long representation
} S_un; //Socket - union
35
IP address and port number
• Both are human unfriendly formats, how to we
convert from and to the appropriate formats?
• Short answer:
• Use given conversion functions...
• htons() to convert port numbers
• “Host to Network Short”
• Also htonl(), ntohs(), ntohl()
• inet_addr() to convert IP addresses
• Which format?? From X.Y.Z.T to binary
• presentation to network”
• Also inet_aton(), inet_pton(), inet_ntop()
36
Programming: Socket Commands
 Creating/closing sockets
socket(int protocol_family, int transport, int zero);
protocol_family is set to PF_INET for TCP/IP or AF_INET.
transport is set to:
 SOCK_STREAM for TCP
 SOCK_DGRAM for UDP
zero is set to 0
Example:
s = socket(PF_INET, SOCK_STREAM, 0);
closesocket(s);
37
Socket Commands (cont.)
 making connections to a remote computer
connect(SOCKET s, struct sockaddr *destaddr, int addrlen);
Example:
connect(s, (struct sockaddr *)&sin, sizeof(sin))
38
Socket Commands (cont.)
 Send data through a socket:
send(SOCKET s, char *msg, int msglen, int flags);
s = socket (inside the socket descriptor: port and IP address...)
msg = a pointer to a buffer (could be a string)
msglen = the length of the buffer
flags = 0
Example:
send(s, sbuffer, strlen(sbuffer),0);
39
Socket Commands (cont.)
 Receive data:
int recv(SOCKET s, char *msg, int msglen, int flags);
s = socket
msg = pointer to a buffer
msglen = length of the buffer
flags = 0
Example:
recv(s, &rbuffer[n], 1, 0);
recv() causes the program to wait
40
Socket Commands (cont.)
 Binding a port to a process (server only):
int bind(SOCKET s, struct sockaddr *localaddr, int addrlen);
A server has to bind port|process, so clients can access a known
port for a service
localaddr = pointer to a local address structure
addrlen = length of localaddr
Example:
bind(s,(struct sockaddr *)(&localaddr),sizeof(localaddr));
41
Socket Commands (cont.)
 Listen (server only):
int listen(SOCKET s, int queuelen);
A server listens using socket s, queues requests if there is
more than one.
The queue limit vary (for windows up to 5).
Example:
listen(s, SOMAXCONN);
listen() runs in the background and stays
running until the socket is closed.
42
Socket Commands (cont.)
 To accept the connection (server only):
accept(SOCKET s, struct sockaddr *addr, int *addrlen);
Example:
ns = accept(s,(struct sockaddr*)(&remoteaddr),&addrlen);
accept() causes the program to wait
43
Socket Commands (cont.)
 gethostbyname(finds an IP address given a name):
struct hostent {
char *h_name;
/*official host name*/
char **h_aliases; /*other aliases*/
short h_addrtype; /*addr type*/
short h_length; /*address length*/
char **h_addr_list; /*list of addresses*/
}*h;
Example:
if ((h=gethostbyname(host)) != NULL){
memcpy(&s.sin_addr, h->h_addr_list, h->h_length);}
else { printf(“error\n”); exit(1); }
44
Simple Client/Server Codes
 Read the client2.c and serv2.c codes carefully.
 Note that the codes are not equipped with
complete error checking.
 Try to follow the logic and the usage of socket
commands
 Do not feel overwhelmed by the awkward syntax!
 Use the debugger as a tool for understanding
programs
45
Using the gcc debugger
 Push 'debug' button
 Use the various options for watching variables
 Where needed use 'cmd' to start either the server
or the client to communicate with the debugging
session
 See the demonstration....
46
memcpy
Copies bytes between buffers.
void *memcpy( void *dest, const void *src, size_t count );
Parameters:
dest - New buffer.
src - Buffer to copy from.
count- Number of characters to copy.
Return Value
- value of dest.
Remarks
- memcpy copies count bytes from src to dest;
47
inet_addr
converts a string containing an (Ipv4) Internet Protocol dotted address
into a proper address for the in_addr structure.
unsigned long inet_addr(
const char FAR* cp
);
Parameters
cp - [in] Null-terminated character string representing a number expressed in the
Internet standard "." (dotted) notation.
Return Value
If no error occurs, this function returns an unsigned long value containing a
suitable binary representation of the Internet address given. If the string in the cp
parameter does not contain a legitimate Internet address, for example if a portion
of an a.b.c.d address exceeds 255, then inet_addr returns the value
INADDR_NONE.
48
inet_ntoa
This function converts an (Ipv4) Internet network address into a string in
Internet standard dotted format.
char FAR* inet_ntoa(
struct in_addr in
);
Parameters
in - [in] Structure that represents an Internet host address.
Return Value
If no error occurs, this function returns a character pointer to a static buffer
containing the text address in standard "." notation. If an error occurs, it returns
NULL.
49
ntohs
The ntohs function converts a u_short from TCP/IP network byte order
to host byte order (which is little-endian on Intel processors).
u_short ntohs(
u_short netshort
);
Parameters
To view the Port number in
human-readable form, e.g.
Port 1444. this is used after
the accept() function is
called.
netshort
[in] 16-bit number in TCP/IP network byte order.
Return Value
The ntohs function returns the value in host byte order. If the netshort parameter
was already in host byte order, then no operation is performed.
Remarks
The ntohs function takes a 16-bit number in TCP/IP network byte order and
returns a 16-bit number in host byte order.
50
Multi-thread
_beginthread
Creates a thread.
uintptr_t _beginthread(
void( *start_address )( void * ),
unsigned stack_size,
void *arglist
);
Let’s see the simple
concurrent addition
example.
start_address
Start address of a routine that begins execution of a new thread.
stack_size
Stack size for a new thread or 0.
arglist
Argument list to be passed to a new thread or NULL.
51
p. 50, RFC 959
52
Assignment: FTP Server
Commands to implement
 USER <SP> <username> <CRLF>
 PASS <SP> <password> <CRLF>
 QUIT <CRLF>
 PORT <SP> <host-port> <CRLF>
 RETR <SP> <pathname> <CRLF>
 STOR <SP> <pathname> <CRLF>
 LIST [<SP> <pathname>] <CRLF>
53
FTP Commands
COMMAND
DESCRIPTION
USER username
User name on the FTP server
PASS password
User’s password on the FTP server
SYST
Type of operating system requested
TYPE type
File type to be transferred: A (ASCII), I
(Image/Binary)
PORT n1,n2,n3,n4,n5,n6
Client IP address (n1-n4) and port number (n5,
n6)
RETR filename.type
Retrieve (get) a file
STOR filename.type
Store (put) a file
LIST filelist
List files or directories
QUIT
Log off from server
Source: Computer Networking and the Internet (5/e) by Fred Halsall
54
FTP Reply Codes
REPLY
DESCRIPTION
1yz
Positive reply, wait for another reply before sending a new command
2yz
Positive reply, a new command can be sent
3yz
Positive reply, another command is awaited
4yz
Negative reply, try again
5yz
Negative reply, do not retry
x0z
Syntax
x1z
Information
x2z
Control or data connection
x3z
Authentication
x4z
Unspecified
x5z
File status
Source: Computer Networking and the Internet (5/e) by Fred Halsall
55
Sample Replies
125 Data connection already open; transfer starting.
150 File status okay; about to open data connection.
200 Command okay.
202 Command not implemented, superfluous at this site.
211 System status, or system help reply.
215 NAME system type.
Where NAME is an official system name from the list in the
Assigned Numbers document.
220 Service ready for new user.
221 Service closing control connection.
Logged out if appropriate.
225 Data connection open; no transfer in progress.
226 Closing data connection.
Requested file action successful (for example, file
transfer or file abort).
227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
230 User logged in, proceed.
250 Requested file action okay, completed.
257 "PATHNAME" created.
331 User name okay, need password.
332 Need account for login.
350 Requested file action pending further information.
56
Sample Replies
421 Service not available, closing control connection.
This may be a reply to any command if the service knows it
must shut down.
425 Can't open data connection.
426 Connection closed; transfer aborted.
450 Requested file action not taken.
File unavailable (e.g., file busy).
451 Requested action aborted: local error in processing.
452 Requested action not taken.
Insufficient storage space in system.
500 Syntax error, command unrecognized.
This may include errors such as command line too long.
501 Syntax error in parameters or arguments.
502 Command not implemented.
503 Bad sequence of commands.
504 Command not implemented for that parameter.
530 Not logged in.
532 Need account for storing files.
550 Requested action not taken.
File unavailable (e.g., file not found, no access).
551 Requested action aborted: page type unknown.
552 Requested file action aborted.
Exceeded storage allocation (for current directory or
dataset).
553 Requested action not taken.
File name not allowed.
57
FTP (Multiple Clients)
TCP Control Socket
C
DIR
Port 127,0,0,1,6,11
Listening
Socket
After file transfer
TCP Control Socket
S
Quit
TCP Active Data Socket
Server
 In TCP, the Server should be running already prior to a
Client connecting to it
58
Active FTP (or Standard )
Standard (or PORT or Active)
The Standard mode FTP client sends PORT commands to the FTP server.
These commands are sent over the FTP command channel when
establishing the FTP session.
Operation
Standard mode FTP clients first establish a connection to TCP port 21 on the
FTP server. This connection establishes the FTP command channel.
The client sends a PORT command over the FTP command channel when
the FTP client needs to send or receive data, such as a folder list or file.
The PORT command contains information about which port the FTP client
receives the data connection on. In Standard mode, the FTP server always
starts the data connection from TCP port 20.
The FTP server must open a new connection to the client when it sends or
receives data, and the FTP client requests this by using the PORT command
again.
59
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Data connection
Port
1120
Port
1121
time
time
Passive open
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
60
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Port
1120
Data connection
Port
1121
Active open
Passive open
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
time
time
61
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Port
1120
Data connection
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
time
time
62
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Port
1120
Data connection
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
time
time
63
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Port
1120
Data connection
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
time
time
64
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Port
1120
Data connection
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
time
time
65
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Port
1120
Data connection
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
time
time
66
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Port
1120
Data connection
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
time
time
67
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Port
1120
Data connection
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
SYST
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
time
time
68
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Port
1120
Data connection
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
SYST
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
time
time
69
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Data connection
Port
1120
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
get <filename.type>
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
time
time
70
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Data connection
Port
1120
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
PORT n1-n6
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
get <filename.type>
time
time
71
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Data connection
Port
1120
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
PORT n1-n6
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
get <filename.type>
time
time
72
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Data connection
Port
1120
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
PORT n1-n6
get <filename.type>
RETR <filename.type>
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
time
time
73
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Data connection
Port
1120
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
PORT n1-n6
get <filename.type>
RETR <filename.type>
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
time
time
time
74
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Data connection
Port
1120
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
PORT n1-n6
Server does an active
open to Port n5, n6
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
get <filename.type>
RETR <filename.type>
time
time
time
75
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Data connection
Port
1120
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
PORT n1-n6
Server does an active
open to Port n5, n6
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
get <filename.type>
RETR <filename.type>
time
time
time
76
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Data connection
Port
1120
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
PORT n1-n6
Server does an active
open to Port n5, n6
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
get <filename.type>
RETR <filename.type>
time
User prompted for a
conmand
time
77
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Data connection
Port
1120
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
PORT n1-n6
Server does an active
open to Port n5, n6
RETR <filename.type>
QUIT
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
get <filename.type>
User prompted for a
conmand
78
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Data connection
Port
1120
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
PORT n1-n6
Server does an active
open to Port n5, n6
RETR <filename.type>
QUIT
time
Source: Computer Networking and the Internet (5/e) by Fred
Halsall
get <filename.type>
User prompted for a
conmand
79
ACTIVE FTP Operation
SERVER
CLIENT
Data connection
control connection
Port
20
Port
21
control connection
Data connection
Port
1120
Port
1121
Active open
Passive open
TCP control connection
to Port 21 established
USER <username>
PASS <password>
PORT n1-n6
Server does an active
open to Port n5, n6
RETR <filename.type>
QUIT
Server closes data connection
time
Source:
Networking
and the connection
Internet (5/e) by Fred
firstComputer
, then
control
Halsall
get <filename.type>
User prompted for a
conmand
80
Where to find more information
• Text book (Kurose and Ross, 2000), Chapter 2.
• Comer, Douglas and Stevens,D., "TCP/IP volume III: Clientserver programming and applications", Prentice Hall 1997.
• Shay, W. A., "Understanding Data Communications &
Networks", ITP 1999 (Chapter 7, item 6).
• Quinn, B. "Windows Sockets Network Programming" AW
1996.
• Web:
www.sockets.com
www.math.grin.edu/~walker/c/sockets-index.html
81
WinSock 1.1 Compatible Name Resolution for TCP/IP
Windows Sockets 1.1 defined a number of routines that were used for name resolution with
TCP/IP (IP version 4) networks. These are customarily referred to as the getXbyY() functions
and include the following:
•
gethostname()
•
•
•
•
•
•
gethostbyaddr()
gethostbyname()
getprotobyname()
getprotobynumber()
getservbyname()
getservbyport()
Asynchronous versions of these functions were also defined:
WSAAsyncGetHostByAddr(), WSAAsyncGetHostByName(), WSAAsyncGetProtoByName()
WSAAsyncGetProtoByNumber(), WSAAsyncGetServByName(), WSAAsyncGetSetvByPort()
There are also two functions (now implemented in the WinSock 2 DLL) used to convert dotted
IPv4 internet address notation to and from string and binary representations, respectively:
•
inet_addr()
•
inet_ntoa()
All of these functions are specific to IPv4 TCP/IP networks and developers of protocolindependent applications are discouraged from continuing to utilize these transport-specific
82
functions.
IPv.4 to IPv.6
 gethostbyname : use getaddrinfo instead
 SOCKADDR_IN : use
SOCKADDR_STORAGE instead, or use
SOCKADDR_IN6 in addition for IPv6
support
 gethostbyaddr : use getnameinfo instead
 AF_INET : use AF_INET6 in addition for
IPv6 support
 inet_addr : use WSAStringToAddress or
getaddrinfo with AI_NUMERICHOST instead
83
FTP (Multiple Clients)
TCP Control Socket
C
DIR
Port 127,0,0,1,6,11
Listening
Socket
After file transfer
TCP Control Socket
S
Quit
TCP Active Data Socket
Server
 In TCP, the Server should be running already prior to a
Client connecting to it
84
Proper Ordering of Send and Recv
socket
socket
bind
connect
listen
/* process the clients request */
loop "forever"
loop until done
{
{
accept /* by creating new socket */
/* process the clients request */
loop until done
{
send/receive
}
closesocket(socket)
receive/send
}
closesocket(newsocket)
}
85
86
Multi-Player Net Game v.1.0
 Network Interface - TCP vs. UDP
 Let’s see the Game!
 Graphical representation of the Network Protocol
 Multi-threaded Server (Code Skeleton)
 Multi-threaded Client (Code Skeleton)
 Keyboard Handling (GetAsyncKeyState)
 Creating and sending packets – string manipulations
 Compiling a multi-file project
 Graphics Programming (Simple Game)
 Flags, Packet Structure, Player Information Structure
87
Multi-Player Net Game v.1.0
This is a proprietary protocol.
TCP Control Socket
C
UDP socket for sending
Listening
Socket (TCP)
TCP Control Socket
Server
S
UDP socket for receiving
3. Server generates UDP
port number based on
client UDP port and sends
it back to client
UDP socket for receiving
UDP socket for sending
4. Game Starts!
1. In TCP, the Server should be running already prior to a Client
connecting to it
2. Client sends commands to inform the server of his/her
name, ip address and port
88
Multi-Player Net Game v.1.1
This is a proprietary protocol.
TCP Control Socket
C
UDP socket for sending
Listening
Socket (TCP)
TCP Control Socket
Server
S
UDP socket for receiving
3. Server generates UDP
port number based on
client UDP port and sends
it back to client
UDP socket for receiving
UDP socket for sending
4. Game Starts!
1. In TCP, the Server should be running already prior to a Client
connecting to it
2. Client sends commands to inform the server of his/her
name, ip address and port
89
Developing the Game
 Creating a Network Interface
 Let’s
see the UDP example (downloadable from
our website)
 TCP
interface (see mindmap and actual codes)
 UDP interface (see mindmap and actual codes)
 What’s the difference between TCP and UDP
connections?
The challenge in the assignment is more of reconnecting the client
After deliberate disconnection without ruining the game (as other
Players might still be playing.
90
Developing the Game
 Creating a Network Interface
for Listening – only port number is required
 Socket for Sending – both IP address and Port
number are required
 TCP Prologue – exchange of messages between
Client and Server (let’s see a simulation)
 Socket
The challenge in the assignment is more of reconnecting the client
After deliberate disconnection without ruining the game (as other
Players might still be playing.
91
Developing the Game
 Creating and sending packets – string
manipulations
 strcpy
 strncmp
 sscanf
 sprintf
SAMPLE MESSAGE:
P
O
R
T
1
1
0
0 CR LF
92
References
 Windows Socket
http://msdn.microsoft.com/en-us/library/windows/desktop/ms740673%28v=vs.85%29.aspx
 Getting Started with Winsock
http://msdn.microsoft.com/en-us/library/windows/desktop/ms738545%28v=vs.85%29.aspx
 Socket Initialisation:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms740496%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms742213(v=vs.85).aspx
93
The End
94
Download