Title: Demonstration programs: Serv2'c and Client2'c
1Socket Programming Materials
- Demonstration programs Serv2.c and Client2.c
- Supporting socket programming materials
- Assignment to be given on Friday
2Getting 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
3Socket 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
4Socket 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
5Client Sockets Server Sockets
6Socket 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
7Socket Programming with TCP
- Naïve example of 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 - Optional exercise modify the serv1.c example to
suit the specifications above.
8Client/Server Socket Interaction TCP
9Client/Server Socket Interaction UDP
10Client/Server Socket Interaction UDP
- No handshaking.
- No streams are attached to the sockets.
- Sender creates packets of bytes with IP
destination address Port number. - Receiving host must unravel each packet received
to obtain the packets information bytes.
11Simple Server Pseudo-Code
- socket
- bind
- listen
- loop "forever"
-
- accept / by creating new socket /
- / process the clients request /
- loop until done
-
- receive/send
-
- closesocket(newsocket)
12Simple Client Pseudo-Code
- socket
- connect
- / process the clients request /
- loop until done
-
- send/receive
-
- closesocket(socket)
13CLIENT-SERVER Demonstration
- Client reads a line from standard input device
(keyboard). - Client sends line out of its socket to the
server. - Server reads a line from its connection socket.
- Server appends extra characters (modifies the
line). - Server sends the modified line out of its
connection socket to the client. - Client reads the line from its socket and prints
the line on its standard output (monitor).
14Some 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.upenn.edu62686
ESTABLISHED TCP IT0270491456
IT027049.massey.ac.nz0 LISTENING TCP
IT0270491456 alb-file2.massey.ac.nznetb
ios-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
15 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
16Winsock application startup
- include ltwinsock.hgt
- define WSVERS MAKEWORD(2,0)
- WSADATA wsadata
- if (WSAStartup(WSVERS,wsadata) ! 0)
- printf(WSAStartup failed\n)
- WSACleanup()
- exit(1)
- When it has completed the use of WinSock, the
application or DLL must call WSACleanup() to
deregister itself from a WinSock implementation
and allow the implementation to free any
resources allocated on behalf of the application
17Programming 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
- assume that sin_family specify TCP/IP
18Programming Data Structures
-
- 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
19Programming 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(SOCKET s)
20Socket Commands (cont.)
- making connections to a remote computer
- connect(SOCKET s, struct sockaddr destaddr, int
addrlen) - Example
- connect(s, (struct sockaddr )sin, sizeof(sin))
- To accept the connection (server only)
- accept(SOCKET s, struct sockaddr addr, int
addrlen) - Example
- ns accept(s,(struct sockaddr)(remoteaddr),add
rlen)
21Socket 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)
22Socket 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)
23Socket 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 stucture
- addrlen length of localaddr
- Example
- bind(s,(struct sockaddr )(localaddr),sizeof(loca
laddr))
24Socket Commands (cont.)
- Listen (server only)
- int listen(SOCKET s, int queuelen)
- A server listens using socket s, queues requests
if there is more then one. - The queue limit vary (for windows up to 5).
- Example
- listen(s,4)
25Socket 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)
26Simple Client/Server Codes
- Read client.c and serv1.c codes
- 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
27Using 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....
28memcpy
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
29inet_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.
30inet_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.
31ntohs
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 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.
To view the Port number in human-readable form,
e.g. Port 1444. this is used after the accept()
function is called.
32Multi-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.
33Where 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
34WinSock 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.
35IPv.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
36FTP (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
37Multi-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
38Multi-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
39Proper 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)
40Multi-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
41Developing 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.
42Developing 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.
43Developing the Game
- Creating and sending packets string
manipulations - strcpy
- strncmp
- sscanf
- sprintf
SAMPLE MESSAGE
P
O
R
T
1
1
0
0
CR
LF
44Developing the Game
- Creating and sending packets string
manipulations - strcpy
- strncmp
- sscanf
- sprintf