You are on page 1of 40

Lab 1 Fundamentals of Socket Programming

Dr. Tony K. C. Chan

Acknowledgements
Thanks for Prof. Y. W. Leung providing valuable materials by which this teaching materials is prepared.

References
[1] D. E. Comer and D. L. Stevens, Internetworking with TCP/IP Volume III: Client-Server Programming and Applications, Prentice-Hall, Inc, 1997. [2] Beejs Guide to Network Programming Using Internet Sockets [Online] Available: http://beej.us/guide/bgnet/ [3] Winsock Functions [Online] Available: http://msdn2.microsoft.com/en-us/library/ms741394.aspx.

1. Review of C Programming
1.1 Some data types

u_char unsigned 8-bit character u_short unsigned 16-bit integer u_long unsigned 32-bit integer

1. Review of C Programming
1.1 Some data types, cont.

structure: a group of different types of data


Example struct info { char name[20]; int id; }; struct info student[40]; student[0].name = Tony; student[0].id = 1234;
5

1. Review of C Programming
1.2 Casting of Data Types

Casting: to change the data type of a variable or expression to the designated one.
Example If x is an int, the data type of the following expression is double (double)(x+1);

1. Review of C Programming
1.3 Pointers

Every memory location has an address we can use this address to access the content in this memory location. A pointer is a variable that stores the memory address (not the value) of a data item.

1. Review of C Programming
1.3 Pointers

Declare a pointer: data-type *pointer-variable; Dereference operator *: *p gives the content stored in the memory location with address p. Address operator &: The address storing the first memory byte of the variable x in &x. Example:
float x, y, *p; p = &x; y = *p; /* declare p as a pointer of float /* assign the address of x to p /* assign the content of p to y
8

1. Review of C Programming
1.4 Pointers and array

The name of an array is actually a pointer to the first element in the array. If x is a one-dimensional array,
The address of the 1st array element is &x[0] or x; The address of the 2nd array element is &x[1] or (x+1);

1. Review of C Programming
1.5 Byte-manipulation functions

We may not use string functions in network programming. Why?

Three byte-manipulation functions

void *memset(void *dest, int chr, int len); void *memcpy(void *dest, const void *src, int len); int memcmp(const void *first, const void *secnd, int len);

memset() specified number of bytes to a value.


Example Stores zeros in a field called x: memset(&x, 0, sizeof(x));

10

1. Review of C Programming
1.5 Byte-manipulation functions

memcpy() copies the value of one field to another


Example Copy the value of y field to the x field: memcpy(&x, &y, sizeof(x));

memcmp() compares two fields


Example Compares the first 10 bytes of fields x and y: if (memcpy(&x, &y,10) == 0) printf(x and y are the same);

11

2. Byte Order

Different computers may have different internal representation of 16/32-bit integer (called host byte order)

Big-endian byte order (e.g., used by Motorola 6800):

12

2. Byte Order

Little-endian byte order (e.g., used by Intel 80x86)

13

2. Byte Order

TCP/IP specifies a network byte order which is the big-endian byte order. Functions for converting between host byte order and network byte order:

u_short htons(u_short host_short); u_short ntohs(u_short network_short); u_long htonl(u_long host_long); u_long ntohl(u_long network_long);

14

3. Endpoint Address

structure holds socket address information for many types of sockets


struct sockaddr { u_short sa_family; /* type of address family */ char sa_data[14]; /* value of address */ }

15

3. Endpoint Address

For TCP/IP, an endpoint address is composed of the following items:

Address family is AF_INET (Address Family for InterNET). Endpoint address in that family is composed of an IP address and a port number.

16

3. Endpoint Address

Port number

A port number identifies an application running on a computer. The port number is composed of 16 bits, and its possible values are used in the following manner:

0-1023: for well-known server applications. 1024-49151: for user-defined server applications. 49152-65535: for client programs.

17

3. Endpoint Address

To deal with struct sockaddr, a compatible structure for TCP/IP endpoint address was created as follows.
struct sockaddr_in { u_short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; }

/* address family */ /* port number */ /* IP address */ /* unused (set to zero) */

18

3. Endpoint Address

The structure of in_addr is as follows.


struct in_addr { u_long s_addr; /* that's a 32-bit long, or 4 bytes */ }

19

3. Endpoint Address

sockaddr and sockaddr_in are compatible:

If you only use TCP/IP, you can use sockaddr_in without using sockaddr.
20

3. Endpoint Address

Example 1

The IP address of a server is 192.168.20.56. Its decimal value is 3232240696. We can specify the endpoint address for this server as follows.
struct sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(2000); serverAddr.sin_addr.s_addr = htonl(3232240696);

21

3. Endpoint Address

Example 1, cont.

Uses inet_addr() converts a string in dotted decimal (e.g., 192.168.20.56) to an integer value suitable for use as an Internet address.
struct sockaddr_in serverAddr; char * serverIP = "192.168.20.56"; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(2000); serverAddr.sin_addr.s_addr = inet_addr(serverIP);

22

3. Endpoint Address

Example 2

We specify the endpoint address for a server as follows:


struct sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(2000); serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); Where the symbolic constant INADDR_ANY represents a wildcard address that matches any of the computer's IP address.
23

Exercises
#pragma comment( linker, "/defaultlib:ws2_32.lib" ) /* Specify the linker to link with ws2_32.lib */ #include <stdio.h> #include <winsock2.h> #define WSVERS MAKEWORD(2, 0) int main(int argc, char *argv[]) { WSADATA wsaData; /* MAKEWORD(2,0): macro creates WORD value */

/* that specifies version 2.0

/* Declare variables */

WSAStartup(WSVERS, &wsaData); /* Initialize socket software */ /* Use socket functions here */ WSACleanup(); return 0; }

/* Deallocate all data structures and socket bindings */

24

Exercises
1. Write a program to print the IP address in 32-bit integer value. 2. If you do not convert the byte order, what happen?

25

4. Details of Each Function Call

General Sequence of Function Calls


CLIENT SIDE
WSAStartup socket

SERVER SIDE
WSAStartup socket

TCP Communications
connect

bind listen accept

send recv closesocket WSACleanup

recv send closesocket WSACleanup


26

4. Details of Each Function Call

Must call WSAStartup() before using socket functions. Example


#define WSVERS MAKEWORD(2, 0) WSADATA wsaData; WSAStartup(WSVERS, &wsaData)
27

4. Details of Each Function Call

Creates a socket Example


SOCKET s; s = socket(PF_INET, SOCK_STREAM, 0)

28

4. Details of Each Function Call


Specifies the endpoint address for a socket. Example


struct sockaddr_in serverAddr;
/* Specify the server's endpoint address in serverAddr here */

bind(s, (struct sockaddr * )&serverAddr, sizeof(serverAddr));


29

4. Details of Each Function Call

Makes socket ready to accept incoming request. Example


listen(s, 1);

30

4. Details of Each Function Call


Establishes connection to a specified remote server Example


struct sockaddr_in serverAddr;
/* Specify the server's endpoint address in serverAddr here */

connect(s, (struct sockaddr * )&serverAddr, sizeof(serverAddr));


31

4. Details of Each Function Call

Accepts the next incoming connection, & return a new socket for the connection Example
struct sockaddr_in clientAddr; Int len; SOCKET ss; ss=accept(s, (struct sockaddr * )&clientAddr, &len);
32

4. Details of Each Function Call

Sends message Example


char *message = "Hello"; send(s, message, strlen(message), 0);

33

4. Details of Each Function Call

Receives message Example


#define BUFMAX 5 char buf[BUFMAX]; recv(s, buf, BUFMAX, 0);

34

4. Details of Each Function Call

Terminates connection Example


closesocket(s);

35

4. Details of Each Function Call

When an application finishes using sockets, it call WSACleanup() to deallocate all data structures and socket bindings. Example
WSACleanup();

36

4. Details of Each Function Call

General Sequence of Function Calls


CLIENT SIDE
WSAStartup socket

SERVER SIDE
WSAStartup socket

TCP Communications
connect

bind listen accept

send recv closesocket WSACleanup

recv send closesocket WSACleanup


37

5. Three simple services of TCP/IP

Three simple services of TCP/IP DAYTIME


Triggered by TCP connection or UDP datagram Return the date and time in a format for human Triggered by TCP connection or UDP datagram Return the time in a 32-bit integer
Return all the data it receives from a client.

TIME

ECHO

38

Exercises
1. Write a TCP client for the DAYTIME service. 2. Write a UDP client for the TIME service. 3. Write a TCP server to provide DAYTIME service. 4. Write a UDP server to provide TIME service. 5. Write a TCP server to provide ECHO service. 6. Write a TCP client for the ECHO service. 7. Repeat 1 - 6 with different sockets. 8. Modify the TIME client so it computes E, the time that elapses between when it sends the request and when it receives a response. Add one-half of E to the time the server sends.
39

THE END
40

You might also like