Socket Programming - PowerPoint PPT Presentation

About This Presentation
Title:

Socket Programming

Description:

Title: Slide 1 Author: nhreyes Last modified by: nhreyes Document presentation format: On-screen Show (4:3) Other titles: Times New Roman Arial Arial Black Comic Sans ... – PowerPoint PPT presentation

Number of Views:123
Avg rating:3.0/5.0
Slides: 95
Provided by: nhreyes
Category:

less

Transcript and Presenter's Notes

Title: Socket Programming


1
Part 1
Socket Programming
IPv6 ready
C/C Language
2
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

3
Socket Programming
  • 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

4
TCP
5
Socket Programming using TCP
  • Socket a door between application process and
    end-end-transport protocol (UDP or TCP)
  • TCP service reliable transfer of bytes from one
    process to another

6
Socket Programming with TCP
  • Client must contact server
  • server process must first be running
  • server must have created socket (door) that
    welcomes clients 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
Client contacts server by creating client-local
TCP socket specifying IP address, port number of
server process
7
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

8
Client/server socket interaction TCP
Server (running on hostid)
Client
Application 2-8
9
Proper Ordering of Send and Recv
  • socket
  • bind
  • listen
  • loop "forever"
  • accept / by creating newsocket /
  • / communicate with client/
  • loop until done
  • receive
  • send
  • closesocket(newsocket)

socket connect / communicate with server/ loop
until done send receive closesocket(soc
ket)
10
Simple Client-Server
C
TCP Control Socket
Listening Socket
S
Temporary TCP Socket for Client
Server
  • In TCP, the Server should be running already
    prior to a Client connecting to it

11
Stream jargon
  • stream is a sequence of 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.

Client process
client TCP socket
Application 2-11
12
UDP
13
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 packets information bytes.

UDP (User Datagram Protocol)
  • No connection state at servers
  • less packet overhead than TCP
  • light error-checking (checksum)
  • server doesnt use the listen() function
  • server doesnt use the accept() function

14
Client/server socket interaction UDP
Server (running on hostid)
create socket, port x.
serverSocket Socket()
Application 2-14
15
Some utility Netstat
Netstat -a
Active Connections Proto Local Address
Foreign Address
State TCP IT027049http
IT027049.massey.ac.nz0 LISTENING TCP
IT027049epmap IT027049.massey.ac.nz0
LISTENING TCP IT027049https
IT027049.massey.ac.nz0 LISTENING TCP
IT027049microsoft-ds IT027049.massey.ac.nz0
LISTENING TCP IT0270491025
IT027049.massey.ac.nz0 LISTENING TCP
IT0270491179 IT027049.massey.ac.nz0
LISTENING TCP IT0270491181
IT027049.massey.ac.nz0 LISTENING TCP
IT0270491300 IT027049.massey.ac.nz0
LISTENING TCP IT0270491318
IT027049.massey.ac.nz0 LISTENING TCP
IT0270491786 IT027049.massey.ac.nz0
LISTENING TCP IT0270491787
IT027049.massey.ac.nz0 LISTENING TCP
IT0270491790 IT027049.massey.ac.nz0
LISTENING TCP IT0270491791
IT027049.massey.ac.nz0 LISTENING TCP
IT0270495000 IT027049.massey.ac.nz0
LISTENING TCP IT02704913450
IT027049.massey.ac.nz0 LISTENING TCP
IT027049netbios-ssn IT027049.massey.ac.nz0
LISTENING TCP IT0270491082
IT027049.massey.ac.nz0 LISTENING TCP
IT0270491179 its-xchg4.massey.ac.nz1165
ESTABLISHED TCP IT0270491181
its-dc2.massey.ac.nz1025 ESTABLISHED TCP
IT0270491318 hnt-up-dhcp-494.wharton.upe
nn.edu62686 ESTABLISHED TCP IT0270491456
IT027049.massey.ac.nz0 LISTENING TCP
IT0270491456 alb-file2.massey.ac.nzne
tbios-ssn ESTABLISHED TCP IT0270491467
IT027049.massey.ac.nz0 LISTENING TCP
IT0270491467 itsa-campus1.massey.ac.nzn
etbios-ssn ESTABLISHED TCP IT0270491786
d226-94-36.home.cgocable.net7091
ESTABLISHED
Displays all active TCP connections and the TCP
and UDP ports on which the computer is listening
16
TCP IT0270491787 pcp0011009611pcs.de
trtc01.mi.comcast.net21848 ESTABLISHED TCP
IT0270491790 balticom-132-227.balticom.l
v63567 ESTABLISHED TCP IT0270491791
24-29-117-20.nyc.rr.com1236 ESTABLISHED TCP
IT0270498947 IT027049.massey.ac.nz0
LISTENING UDP IT027049microsoft-ds
UDP IT027049isakmp
UDP IT0270491026
UDP
IT0270491027
UDP IT0270491028
UDP IT0270491046
UDP IT0270491088
UDP IT0270491177
UDP IT02704913450
UDP
IT02704938037
UDP IT027049ntp
UDP IT0270491187
UDP IT0270491459
UDP IT0270491718
UDP IT0270491900
UDP
IT027049ntp
UDP IT027049netbios-ns
UDP IT027049netbios-dgm
UDP IT0270491900
UDP IT0270498760
UDP IT02704962493

17
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

18
TCP Server
IPv6 ready
19
Winsock application startup
Headers required
  • //Ws2_32.lib
  • define _WIN32_WINNT 0x501 //to recognise
    getaddrinfo()
  • include ltwinsock2.hgt
  • include ltws2tcpip.hgt
  • include ltstdlib.hgt
  • include ltstdio.hgt
  • //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
20
Winsock application startup
makefile
Name of your program
  • server.exe server.o
  • g -Wl,-s -o server.exe server.o -lws2_32
  • server.o server.cpp
  • g -c -fpermissive -fconserve-space server.cpp

If compiling using Scite,
Select Tools, then Build (or CtrlF7)
21
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.
  • define WSVERS MAKEWORD(2,2)

Ver.2.2
22
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)

23
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")

24
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.
25
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-gtai_family, result-gtai_socktype,
    result-gtai_protocol)
  • //check for errors in socket allocation
  • if (s INVALID_SOCKET)
  • printf("Error at socket() ld\n",
    WSAGetLastError())
  • freeaddrinfo(result)
  • WSACleanup()
  • exit(1)

26
Winsock application startup
Bind the socket to the Servers IP address and
port number
  • int iResult bind(s, result-gtai_addr,
    (int)result-gtai_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

27
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
28
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),ad
    drlen)
  • if (ns INVALID_SOCKET)
  • printf("accept failed d\n",
    WSAGetLastError())
  • closesocket(s)
  • WSACleanup()
  • return 1
  • 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)

Once an incoming client is detected, a new socket
is created to accept the client for connection.
29
Winsock application startup
Communicate with the client (receive, process,
send message).
  • while (1)
  • n 0
  • while (1)
  • bytes recv(ns, receive_buffern, 1,
    0)
  • if ((bytes SOCKET_ERROR) (bytes
    0)) break
  • if (receive_buffern '\n')
    /end on a LF/
  • receive_buffer n '\0'
  • break
  • if (receive_buffern ! '\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

Remove delimeters
30
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)
  • WSACleanup()
  • exit(1)
  • closesocket(ns)
  • printf("\ndisconnected from
    s\n",inet_ntoa(remoteaddr.sin_addr))

shutdown the send half of the connection since no
more data will be sent
31
Winsock application startup
Shutdown the server
  • closesocket(s)
  • WSACleanup()
  • / call WSACleanup when done using the Winsock
    dll /

To release the allocated resources.
32
Functions and Data Structures
33
Winsock application startup
C\Windows\System32\WS2_32.dll
  • include ltwinsock.hgt
  • define WSVERS MAKEWORD(2, 2)
  • WSADATA wsadata
  • 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-u
s/library/windows/desktop/aa38375128vvs.8529.as
px
34
Programming Data Structures
  • sockaddr_in
  • struct sockaddr_in
  • short sin_family
  • u_short sin_port
  • struct in_addr sin_addr
  • char sin_zero8
  • 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

35
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

36
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()

37
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)

38
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))

39
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)

40
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, rbuffern, 1, 0)

recv() causes the program to wait
41
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 portprocess, 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(loca
    laddr))

42
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.
43
Socket Commands (cont.)
  • To accept the connection (server only)
  • accept(SOCKET s, struct sockaddr addr, int
    addrlen)
  • Example
  • ns accept(s,(struct sockaddr)(remoteaddr),add
    rlen)

accept() causes the program to wait
44
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 ((hgethostbyname(host)) ! NULL)
  • memcpy(s.sin_addr, h-gth_addr_list,
    h-gth_length)
  • else printf(error\n) exit(1)

45
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

46
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....

47
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
48
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.
49
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.
50
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
  • )

To view the Port number in human-readable form,
e.g. Port 1444. this is used after the accept()
function is called.
Parameters 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.
51
Multi-thread
_beginthread
Creates a thread.
  • uintptr_t _beginthread(
  • void( start_address )( void ),
  • unsigned stack_size,
  • void arglist
  • )

Lets 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.
52
Active FTP mode
p. 50, RFC 959
53
Assignment FTP Server
  • Commands to implement
  • USER ltSPgt ltusernamegt ltCRLFgt
  • PASS ltSPgt ltpasswordgt ltCRLFgt
  • QUIT ltCRLFgt
  • PORT ltSPgt lthost-portgt ltCRLFgt
  • RETR ltSPgt ltpathnamegt ltCRLFgt
  • STOR ltSPgt ltpathnamegt ltCRLFgt
  • LIST ltSPgt ltpathnamegt ltCRLFgt

54
FTP Commands
COMMAND DESCRIPTION
USER username User name on the FTP server
PASS password Users 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
55
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
56
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.
57
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.
58
FTP (Multiple Clients)
C
TCP Control Socket
DIR
Port 127,0,0,1,6,11
Listening Socket
After file transfer
TCP Control Socket
Quit
S
TCP Active Data Socket
Server
  • In TCP, the Server should be running already
    prior to a Client connecting to it

59
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.
60
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Passive open
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
61
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
62
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
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
63
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
64
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
65
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
66
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
67
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
68
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
SYST
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
69
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
SYST
215 UNIX TypeX VersionY
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
70
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
get ltfilename.typegt
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
71
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
PORT n1-n6
get ltfilename.typegt
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
72
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
PORT n1-n6
get ltfilename.typegt
200 PORT command successful
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
73
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
PORT n1-n6
get ltfilename.typegt
200 PORT command successful
RETR ltfilename.typegt
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
74
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
PORT n1-n6
get ltfilename.typegt
200 PORT command successful
RETR ltfilename.typegt
150 opening ASCII mode data connection
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
75
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
PORT n1-n6
get ltfilename.typegt
200 PORT command successful
Server does an active open to Port n5, n6
RETR ltfilename.typegt
150 opening ASCII mode data connection
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
76
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
PORT n1-n6
get ltfilename.typegt
200 PORT command successful
Server does an active open to Port n5, n6
RETR ltfilename.typegt
150 opening ASCII mode data connection
Send file through data connection
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
77
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
PORT n1-n6
get ltfilename.typegt
200 PORT command successful
Server does an active open to Port n5, n6
RETR ltfilename.typegt
150 opening ASCII mode data connection
Send file through data connection
226 File transfer complete
User prompted for a conmand
time
Source Computer Networking and the Internet
(5/e) by Fred Halsall
78
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
PORT n1-n6
get ltfilename.typegt
200 PORT command successful
Server does an active open to Port n5, n6
RETR ltfilename.typegt
150 opening ASCII mode data connection
Send file through data connection
226 File transfer complete
QUIT
User prompted for a conmand
Source Computer Networking and the Internet
(5/e) by Fred Halsall
79
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
PORT n1-n6
get ltfilename.typegt
200 PORT command successful
Server does an active open to Port n5, n6
RETR ltfilename.typegt
150 opening ASCII mode data connection
Send file through data connection
226 File transfer complete,
QUIT
User prompted for a conmand
221 Goodbye
Source Computer Networking and the Internet
(5/e) by Fred Halsall
80
ACTIVE FTP Operation
CLIENT
SERVER
Data connection
control connection
Data connection
control connection
Port 20
Port 21
Port 1120
Port 1121
Active open
Passive open
TCP control connection to Port 21 established
220 FTP server ready
USER ltusernamegt
331 password required
PASS ltpasswordgt
220 user ltusernamegt logged in
PORT n1-n6
get ltfilename.typegt
200 PORT command successful
Server does an active open to Port n5, n6
RETR ltfilename.typegt
150 opening ASCII mode data connection
Send file through data connection
226 File transfer complete,
QUIT
User prompted for a conmand
Server closes data connection first , then
control connection
221 Goodbye
Source Computer Networking and the Internet
(5/e) by Fred Halsall
81
Where to find more information
  • Text book (Kurose and Ross, 2000), Chapter 2.
  • Comer, Douglas and Stevens,D., "TCP/IP volume
    III Client-server 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

82
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() gethostby
addr() gethostbyname() getprotobyname() getp
rotobynumber() 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() ine
t_ntoa() All of these functions are specific to
IPv4 TCP/IP networks and developers of
protocol-independent applications are discouraged
from continuing to utilize these
transport-specific functions.
83
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

84
FTP (Multiple Clients)
C
TCP Control Socket
DIR
Port 127,0,0,1,6,11
Listening Socket
After file transfer
TCP Control Socket
Quit
S
TCP Active Data Socket
Server
  • In TCP, the Server should be running already
    prior to a Client connecting to it

85
Proper Ordering of Send and Recv
socket connect / process the clients request
/ loop until done send/receive closesocke
t(socket)
  • socket
  • bind
  • listen
  • loop "forever"
  • accept / by creating new socket /
  • / process the clients request /
  • loop until done
  • receive/send
  • closesocket(newsocket)

86
Some Extras
87
Multi-Player Net Game v.1.0
  • Network Interface - TCP vs. UDP
  • Lets 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

88
Multi-Player Net Game v.1.0
This is a proprietary protocol.
C
TCP Control Socket
UDP socket for receiving
UDP socket for sending
Listening Socket (TCP)
3. Server generates UDP port number based on
client UDP port and sends it back to client
TCP Control Socket
S
UDP socket for receiving
Server
4. Game Starts!
UDP socket for sending
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
Multi-Player Net Game v.1.1
This is a proprietary protocol.
C
TCP Control Socket
UDP socket for receiving
UDP socket for sending
Listening Socket (TCP)
3. Server generates UDP port number based on
client UDP port and sends it back to client
TCP Control Socket
S
UDP socket for receiving
Server
4. Game Starts!
UDP socket for sending
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
90
Developing the Game
  • Creating a Network Interface
  • Lets see the UDP example (downloadable from our
    website)
  • TCP interface (see mindmap and actual codes)
  • UDP interface (see mindmap and actual codes)
  • Whats 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.
91
Developing the Game
  • Creating a Network Interface
  • Socket 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 (lets see a simulation)

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.
92
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
93
References
  • Windows Socket
  • http//msdn.microsoft.com/en-us/library/windows/d
    esktop/ms74067328vvs.8529.aspx
  • Getting Started with Winsock
  • http//msdn.microsoft.com/en-us/library/windows/d
    esktop/ms73854528vvs.8529.aspx
  • Socket Initialisation
  • http//msdn.microsoft.com/en-us/library/windows/d
    esktop/ms74049628vvs.8529.aspx
  • http//msdn.microsoft.com/en-us/library/windows/de
    sktop/ms742213(vvs.85).aspx

94
The End
Write a Comment
User Comments (0)
About PowerShow.com