Chapter 2
Chapter 2
Programming Review
School of Information and Communication Technology,
Hanoi University of Science and Technology
References
[1] W.Richard Stevens, Unix Network Programming Vol.1, 3rd Ed., Prentice
Hall.
[2] Keir Davis, John W. Turner, and Nathan Yocom, The Definitive Guide to
Linux Network Programming, Apress.
[3] Michael Donahoo, Kenneth Calvert, TCP/IP Sockets in C: Practical Guide
for Programmers, Elsevier.
2
Content
• Creating, Compiling and Running Your Program
• C/C++ Basics
• C/C++ Advances
• Input and Output
• String Handling
• File Access and Directory System Calls
• Process Control
3
Creating, Compiling and Running
• There are a number of compilers
• cc (Sun Solaris)
• bcc (Borland)
• gcc
5
Creating, Compiling and Running
• Useful options
• -c: suppress linking, produce object files only
• -l<lib>: link with library
cc calc.c -o calc –lm
• -L<dir>: add directory to the library searching path
cc prog.c -L/home/myname/mylibs mylib.a
• -I<dir>: add directory to the header searching path
• -g: enable debugging with gdb
6
C/C++ Basics
• Data types
• char, short, int, long
• float, double
• array
• string
• Conditions
• if-else
• switch-case
• Looping and Iteration
• for
• while
• do-while
7
C/C++ Advances
• Pointer
• A variable which
contains the
address in
memory of
another variable
8
C/C++ Advances
• We can do integer arithmetic on a pointer
9
Excercise
• Input a float number
• Using pointer to access its memory and
• Print 4 bytes representing the float number
• Using a simple value (Ex: 1.5) to validate the IEEE
754 representation MANUALLY
10
C/C++ Advances
• Pointers and arrays are very closely linked in C
int a[10], x;
int *pa;
pa = &a[0]; /* pa pointer to address of a[0] */
x = *pa;
/* x = contents of pa (a[0] in this case) */
11
C/C++ Advances
• Dynamic Memory Allocation
• memset(pointer, value, bytecount)
• memcpy(dest_pointer, src_pointer, bytecount);
• void *malloc(size_t number_of_bytes)
int *ip;
ip = (int *) malloc(100*sizeof(int));
• void *calloc(size_t num_elements, size_t element_size}
ip = (int *) calloc(100, sizeof(int));
• void *realloc( void *ptr, size_t new_size);
ip = (int*) realloc(ip, 101 * sizeof(int));
12
Excercise
• Input a float from the stdin until a ZERO is entered
• Store all the float values into a dynamically-
allocated array (use malloc, alloc, realloc)
• Print out the sum of those floats
13
C/C++ Advances
• Pointers to pointers
char ch; /* a character */
char *pch; /* a pointer to a character */
char **ppch; /* a pointer to a pointer to a character */
14
C/C++ Advances
• Pointer to functions
• Store the address of a function in a pointer
• Passing and calling function using variables
• Very useful to provide call-back mechanism in many
application
typedef void (*printer_t)(int);
void print_to_n(int n)
{
for (int i = 1; i <= n; ++i) printf("%d\n", i);
}
printer_t p = &print_to_n;
p(5); // Prints 1 2 3 4 5 on separate lines
15
Input and Output
• #include <stdio.h>
• Reporting Errors
• perror()
• errno
• exit()
• Streams
• stdin
• stdout
• stderr
16
Input and Output
• stdin and stdout can be used with files, programs,
I/O devices such as keyboard, console, etc.
• stderr always goes to the console or screen
• The console is the default for stdout and stder
• The keyboard is the default for stdin
• Predefined stream are automatically open
• Stream redirection (OS command line)
• prog1 > file1: send output to a file
• prog2 < file2: input from a file
• prog1 | prog2: pipe stdout of prog1 to stdin of prog2
17
Input and Output
• int getchar(void)
• int putchar(char ch)
• int printf(char *format, arg
list ...)
• int scanf(char *format,
args....)
• int sprintf(char *string,
char *format, args..)
• int sscanf(char *string,
char *format, args..)
18
Input and Output
• Files
• FILE *fopen(char *name, char *mode)
• Reading: mode = “rt”, “rb”
• Writing: mode = “wt”, “wb”
• Appending: mode = “at”, “ab”
• int fprintf(FILE *stream, char *format, args..)
• int fscanf(FILE *stream, char *format, args..)
• fwrite, fread
• int getc(FILE *stream)
• int fgetc(FILE *stream)
• int putc(char ch, FILE *s)
• int fputc(char ch, FILE *s)
• fflush(FILE *stream)
• fclose(FILE *stream)
19
Input and Output
• Stream Status Enquiries
• int feof(FILE *stream);
• int ferror(FILE *stream);
• void clearerr(FILE *stream);
• int fileno(FILE *stream);
20
Input and Output
• Low Level I/O
• This form of I/O is UNBUFFERED
• There are no formatting facilities
• This means we are now using binary (and not text) files
• int open(char *filename, int flag, int perms)
• flag = O_APPEND, O_CREAT, O_RDWR...
• Perms = 0 for most applications
• Return a file descriptor or -1 (failed)
• int close(int handle) -- close a file
• int read(int handle, char *buffer, unsigned length)
• int write(int handle, char *buffer, unsigned length)
21
String Handling
• #include <string.h>
• char *stpcpy (char *dest,const char *src) -- Copy one string into another.
• int strcmp(char *string1,const char *string2) - Compare string1 and string2 to
determine alphabetic order.
• char *strcpy(char *string1,const char *string2) -- Copy string2 to stringl.
• char *strerror(int errnum) -- Get error message corresponding to specified error
number.
• size_t strlen(const char *string) -- Determine the length of a string.
• char *strncat(char *string1, char *string2, size_t n) -- Append n characters from
string2 to stringl.
• int strncmp(char *string1, char *string2, size_t n) -- Compare first n characters of
two strings.
• char *strncpy(char *string1,const char *string2, size_t n) -- Copy first n characters
of string2 to stringl .
• int strcasecmp(const char *s1, const char *s2) -- case insensitive version of
strcmp().
• int strncasecmp(const char *s1, const char *s2, int n) -- case insensitive version
of strncmp().
22
String Handling
• Searching
• char *strchr(const char *string, int c) -- Find first occurrence of character c in
string.
• char *strrchr(const char *string, int c) -- Find last occurrence of character c in
string.
• char *strstr(const char *s1, const char *s2) -- locates the first occurrence of the
string s2 in string s1.
• char *strpbrk(const char *s1, const char *s2) -- returns a pointer to the first
occurrence in string s1 of any character from string s2, or a null pointer if no
character from s2 exists in s1
• size_t strspn(const char *s1, const char *s2) -- returns the number of
characters at the begining of s1 that match s2.
• size_t strcspn(const char *s1, const char *s2) -- returns the number of
characters at the begining of s1 that do not match s2.
• char *strtok(char *s1, const char *s2) -- break the string pointed to by s1 into a
sequence of tokens, each of which is delimited by one or more characters from
the string pointed to by s2.
• char *strtok_r(char *s1, const char *s2, char **lasts) -- has the same
functionality as strtok() except that a pointer to a string placeholder lasts must
be supplied by the caller.
23
Memory Operations
• void *memchr (void *s, int c, size_t n) -- Search for
a character in a buffer .
• int memcmp (void *s1, void *s2, size_t n) --
Compare two buffers.
• void *memcpy (void *dest, void *src, size_t n) --
Copy one buffer into another .
• void *memmove (void *dest, void *src, size_t n) --
Move a number of bytes from one buffer lo another.
• void *memset (void *s, int c, size_t n) -- Set all
bytes of a buffer to a given character.
24
File Access & Directory System Calls
• int chdir(char *path) -- changes directory to
specified path string
• char *getwd(char *path) -- get the full pathname of
the current working directory
• scandir(char *dirname, struct dirent **namelist,
NULL, NULL)
• int access(char *path, int mode) -- determine
accessibility of file, return 0 for success or -1 for
failure. mode = R_OK, W_OK, X_OK, F_OK
• int stat(char *path, struct stat *buf)
• int fstat(int fd, struct stat *buf)
25
File Access & Directory System Calls
26
File Access & Directory System Calls
• int remove(const char *path);
• int rename(const char *old, const char *new);
• FILE *tmpfile(void) creates a temporary file and
opens a corresponding stream. The file will
automatically be deleted when all references to the
file are closed.
27
Process Control
• A process is basically a single running program
• Running UNIX Commands from C/C++
• int system(char *string)
main()
{
printf("Files in Directory are:\n");
system("ls -l");
}
• system is a call that is made up of 3 other system calls:
execl(), wait() and fork()
28
Exercise 1
• Using system to excute “ifconfig” and display all the IPs of
the linux machine
• Using system to excute “ls –a –l” and display a list of file
including names and sizes
• Using scandir to build a list of sub folders and files. Display
the result in html format like below:
<a href = “FolderA”><b>FolderA</b></a>
<a href = “FolderB”><b>FolderB</b></a>
<a href = “FileName1><i>FileName1</i></a>
<a href = “FileName2><i>FileName2</i><a/></html>
• Root Path: “/”
• Wait for a text input, check if
• It is a folder in the current path: go into the folder and list again
• It is “..” go up (if the current folder is not the root) and list again
29
Process Control
• execl(): execute and leave
• execl(char *path, char *arg0,...,char *argn, 0)
main()
{
printf("Files in Directory are:\n");
execl("/bin/ls","ls", "-l",0);
}
30
Process Control
• int fork() turns a single process into 2 identical processes, known as
the parent and the child
• The child process will have its own unique PID
main()
{
int return_value;
printf("Forking process\n");
fork();
printf(“ The process id is %d
and return value is %d\n",
getpid(), return_value);
execl("/bin/ls/","ls","-l",0);
printf("This line is not printed\n");
}
31
Process Control
• int wait (int *status_location) -- will force a parent
process to wait for a child process to stop or
terminate
• wait() return the pid of the child or -1 for an error
• void exit(int status) -- terminates the process which
calls this function and returns the exit status value
32
Q&A
33
Project 1 (Max 10)
• POP3 eMail client
• Connect to a POP3 mail server (local or global)
• Login
• Get email list and status
• Get email’s content (include attachment)
• Send email to a user with attachment
34
Project 2 (Max 10)
• SMTP eMail client
• Connect to a SMTP mail server (local or global)
• Login
• Get email list and status
• Get email’s content (include attachment)
• Send email to a user with attachment
35
Project 3 (Max 9)
• FTP Client (Standard Protocol)
• Connect to a FTP Server
• Login
• Get file list
• Change directory
• Download and upload files
36
Project 4 (Max 8.5)
• Chat room server
• Server
• Maintains a list of client accounts
• Maintains a list of rooms
• Forward messages from a client to others in the same room
• Client
• Login to the server
• Get the list of rooms and join one room
• Send message to chat with others in the same room
• Leave the room
• Define your own protocol
37
Project 5 (Max 10)
• P2P File Share
• Define your own P2P file sharing protocol
• A tracking server to maintain information about files to be
shared and locations of those files
• Tracking server return the file’s information to a client
• Clients work together to get the requested file
38
Project 6 – IRC Chat Client (Max 8.5)
• Connect to a local IRC chat server
• Send joining request
• Send and receive messages from a channels
39
Project 7a (Text-Based) (Max 8.5)
• Caro chess server
• Maintain a list of player accounts
• Maintain a list of playing boards
• Update a board when receiving input from a player
• Check if a game is finished and send winning
announcement to the players and finish the game
• Caro chess client
• Login to the server
• Match with a free player (who is not playing any game)
• Start the game until it is finished by the server or the
player can quit the game
• Define your own protocol
40
Project 7b (Binary-Based) (Max 8.5)
• Caro chess server
• Maintain a list of player accounts
• Maintain a list of playing boards
• Update a board when receiving input from a player
• Check if a game is finished and send winning
announcement to the players and finish the game
• Caro chess client
• Login to the server
• Match with a free player (who is not playing any game)
• Start the game until it is finished by the server or the
player can quit the game
• Define your own protocol
41
Project 8a (Text-Based) (Max 8.5)
• Chess server
• Maintain a list of player accounts
• Maintain a list of playing boards
• Update a board when receiving input from a player
• Check if a game is finished and send winning
announcement to the players and finish the game
• Chess client
• Login to the server
• Match with a free player (who is not playing any game)
• Start the game until it is finished by the server or the
player can quit the game
• Define your own protocol
42
Project 8b (Binary-Based) (Max 8.5)
• Chess server
• Maintain a list of player accounts
• Maintain a list of playing boards
• Update a board when receiving input from a player
• Check if a game is finished and send winning
announcement to the players and finish the game
• Chess client
• Login to the server
• Match with a free player (who is not playing any game)
• Start the game until it is finished by the server or the
player can quit the game
• Define your own protocol
43
Project 9a (Max 8.5)
• Define your own text-based FTP protocol and
implement
• FTP client
• FTP server
• Your FTP client and server should be able to
• Handle user account and home folder
• Handle user login
• Handle multiple clients
• Handle file downloading and uploading like the well-
known FTP protocol
• Your protocol can be simpler than the well-known
FTP protocol
44
Project 9b (Max 8.5)
• Same as 9a but the protocol is binary-based
45