0% found this document useful (0 votes)
35 views

Lec01 ReviewCProgramming

The result will be a=3, b=5. This is because x and y in swap() are local variables that do not affect a and b in main(). To swap the values, pointers must be used.

Uploaded by

An Nguyễn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Lec01 ReviewCProgramming

The result will be a=3, b=5. This is because x and y in swap() are local variables that do not affect a and b in main(). To swap the values, pointers must be used.

Uploaded by

An Nguyễn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

NETWORK PROGRAMING

Tong Van Van, SoICT, HUST

1
Lecturer Information
Dr. Tong Van Van
School of Information and Communication Technology,
Hanoi University of Science and Technology

• Office : 405-B1
• E-mail : [email protected]
• Google Scholar:
https://scholar.google.com/citations?user=XKJm_fQAAAA
J&hl=en

2
Course information
• IT4062: Network programming
• What we study in this course
▪ How to build network applications using socket programming
paradigm.
▪ Socket programming using C (in details)

3
Course information
• References
▪ Documents of professional group related to subject: Network
Programming.
▪ Unix Network Programming Vol.1, 3rd edition, W.Richard Stevens,
Prentice-Hall
▪ Internetworking with TCP/IP vol.3, Client-Server Programming
and Applications (BSD version), Douglas E. Comer, David L.
Stevens, Prentice-Hall
▪ TCP/IP Sockets in C: Practical Guide for Programmers, Michael
Donahoo, Kenneth Calvert, Elsevier Science

4
Course information
• Exercises in class
▪ After each lecture
▪ Used for mid-term evaluation
• Final project
▪ Development of network applications in groups
▪ 2-3 members/ group
▪ Used for final evaluation
• Grading
▪ Exercises (50%)
▪ Final project (50%)

5
Course information
• Email for submitting exercises: [email protected]

• Subject: Homework X

• You must store the files containing source code in a directory.


The directory is compressed and named by
Name_StudentID_HWx. Besides, x is the sequence number of
the homework.
• Dateline for homework: Before subsequent session.
• Cheating and plagiarism: You will FAIL this course.
• Testing environment: Ubuntu 22.04, GCC compiler
• HW Grading
• Functionality: 70%
• Clean code (comment, naming, modular design, v.v): 30%
6
Course contents
• Lecture contents
▪ Review of C programming language
▪ Review of related concept in Computer Networks
▪ Introduction to Socket API
▪ Basic TCP socket: server side, client side
▪ UDP socket
▪ Multi-process TCP server
▪ Application protocol

7
REVIEW C PROGRAMING
Tong Van Van, SoICT, HUST

8
Content
• Data type
• Condition and Iteration
• Function
• Command line argument
• Pointer
• Structure
• Link listed
• I/O function

9
Data type
• Integer
• int, char, short, long
• Floating
• double, float
• Array
• Collection of A data type
• Declare : int a[10];

10
Size of Type

• size of char: 1 bytes s -128~+127


76 0

• size of short: 2 bytes s -32768~+32767


15 14 0
• size of int: 4 bytes s
31 30 0
• size of long: 4 bytes -2147483648~+2147483647

• size of float: 4 bytes

• size of double: 8 bytes s


63 62 0
-1.7E-308 ~1.7E+308

11
Condition and Loop Structure
• if … else
• switch
• for
• while, do … while

12
Condition
• a == b
• b equals to a
• a != b
• b is different to a
• a>b
• b is smaller than a
• a >= b
• b isn’t greater than a
• a<b
• b is greater than a
• a <= b
• b isn’t smaller than a

13
if … else
if(condition){ if (condition)
statement1; task1;
… else task2;
}
else{
statement2; is equivalent?

}
if (condition)
task1;
Example :
if (!condition)
if( x == 1){
task2;
y = 3;
z = 2;
}
else{
y = 5;
z = 4;
}
14
switch
switch(condition){
case value1: statement1;…; break;
case value2: statement2;…; break;

default: statement;…; break;
}

Example :
int monthday( int month ){
switch(month){
case 1: return 31;
case 2: return 28;

case 12: return 31;
}
}

15
for
• expr1, expr3: assignments or function calls
• expr2: relational expression
Any of the three expression can be omitted
• the semicolons must remain

for(expr1;expr2;expr3){
statements;

}

Example:
for( x = 0; x < 10; x++){
printf(“%d\n”, x);
}

16
while, do…while
• If there is no initialization or re-initialization, the while is
most natural
while ((c = getchar()) == ' ' || c == '\n' || c = '\t')
/* skip white space characters *

while(condition){ do{
statement; statement;
… …
} } while(condition)

Example: Example:
x = 0; x = 0;
while(x < 10){ do{
printf(“%d\n”,x); printf(“%d\n”,x);
x = x + 1; x = x + 1;
} } while(x < 10)
17
break
• break
• Terminates the execution of the nearest enclosing loop or conditional
statement in which it appears.
• continue
• Pass to next iteration of nearest enclosing do, for, while statement in
which it appears
• Example
/* trim: remove trailing blanks, tabs, newlines */
char s[MAX]
int n;
for (n = strlen(s)-1; n >= 0; n--)
if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n')
break;
s[n+1] = '\0';

for (i = 0; i < n; i++)


if (a[i] < 0) /* skip negative elements */
continue;
... /* do positive elements */ 18
Function
• A function is a group of statements that is executed when it is called
from some point of the program. The following is its format:
type name ( parameter1, parameter2, ...) {
statements;
}
• where:
• type is the data type specifier of the data returned by the
function.
• name is the identifier by which it will be possible to call the
function.
• parameters (as many as needed): Each parameter consists of a
data type specifier followed by an identifier
• statements is the function's body. It is a block of statements
surrounded by braces { }.

19
Example of function
#include <stdio.h>
int squaresub(int a)
{ Data type of function
return a*a;
} Return value statement

int main()
{
int b = 10;
printf("%d\n", squaresub(5));
return 0; Use function
}

20
Usage of command line arguments
• main( int argc, char **argv) Example :
• main( int argc, char *argv[]) %./a.out 123 456 789
arg[0]: ./a.out
• Argc : number of arguments arg[1]: 123
• argv[0] : argument 0 arg[2]: 456
• argv[1] : argument 1 arg[3]: 789
• argv[2] : argument 2

21
Pointer
Address
• Pointer variable
• "Variable" refers to
variable 108 i
• int i = 10;
104 j
• int j = 20;
100 ptr
• int *ptr;
• Pointer to pointer:
int **p;
0 Variables and addresses

22
Pointer (cont)
Address
• int i = 10;
• int j = 20;
• int *ptr = &i; 108 i 10
104 j 20
• printf(“i=%d\n”, &i)
100 ptr 108
• printf(“ptr=%d\n”, ptr)
• printf(“i=%d\n”, i)
• printf(“*ptr=%d\n”,*ptr)
• Ptr refers to the pointer variable 0
Variables and addresses

23
Pointer (cont)
• int x=1, y=5;
• int z[10];
• int *p;
• p=&x; /* p refers to x */
• y=*p; /*y is assigned the value of x*/
• *p = 0; /* x = 0 */
• p=&z[2]; /* p refer to z[2] */

24
Pointer and function
#include <stdio.h>
void swap(int x, int y) Result ?
{
int temp;
temp = x;
x = y;
y = temp;
}

int main(){
int a = 5;
int b = 3;
swap (a, b);
printf(“a=%d\n”, a);
printf(“b=%d\n”, b);
return 0;
}

25
Pointer and function (cont)
#include <stdio.h>
void swap(int x, int y) Address
{
int temp; 108 a
temp = x;
x = y; 104 b
y = temp;
}

int main(){ Exchange


94 x 5
int a = 5;
int b = 3; 90 y
swap (a, b); 3
printf(“a=%d\n”, a);
printf(“b=%d\n”, b);
return 0; 0
}

26
Pointer and function (cont)
#include <stdio.h> Program to exchange 2 value of variables
void swap(int *x, int *y)
{
int temp; 108 a *x
temp = *x;
*x = *y; 104 b *y
*y = temp;
}

int main(){
int a = 5; 94 x 108
int b = 3;
90 y 104
swap (&a,&b);
printf(“a=%d\n”, a);
printf(“b=%d\n”,b);
return 0;
} 0

27
Pointer and Array
• The declaration an integer array a[0] a[1] … … … a[9]
int a[10];
• If pa is a pointer to an integer:
int *pa; pa pa+1 pa+2
pa = &a[0];
• Similarity: pa and a are pointers
• Difference: pa is a variable but a is not
• legal: pa ++; pa = a;
• Illegal: a++; a = pa;
• a: constant pointer

28
Constant pointer vs Pointer to constant

• Constant pointer: a pointer that cannot change the


address its holding.
• Declaration: <type> *const <name of pointer>

• Pointer to constant: a pointer through which one cannot


change the value of variable it points
• Declaration: const <type>* <name of pointer>

• Constant Pointer to a Constant: mixture of the above two


types of pointers
• Declaration:
const <type of pointer>* const <name of pointer>

29
Constant pointer
#include <stdio.h>
int main(void)
{
int var1 = 0, var2 = 0;
int *const ptr = &var1;
ptr = &var2;
printf("%d\n", *ptr);

return 0;
}

$ gcc -Wall constptr.c -o constptr


constptr.c: In function ‘main’:
constptr.c:7: error: assignment of read-only variable
‘ptr’

30
Pointer to constant
#include <stdio.h>
int main(void)
{
int var1 = 0;
const int* ptr = &var1;
*ptr = 1;
printf("%d\n", *ptr);

return 0;
}

$ gcc -Wall constptr.c -o constptr


constptr.c: In function ‘main’:
constptr.c:7: error: assignment of read-only location
‘*ptr’

31
Constant Pointer to a Constant
#include <stdio.h>
int main(void)
{
int var1 = 0,var2 = 0;
const int* const ptr = &var1;
*ptr = 1;
ptr = &var2;
printf("%d\n", *ptr);

return 0;
}

$ gcc -Wall constptr.c -o constptr


constptr.c: In function ‘main’:
constptr.c:7: error: assignment of read-only location
‘*ptr’
constptr.c:8: error: assignment of read-only variable
‘ptr’
32
Return pointer from functions vs
Function pointer
• Return pointer from functions:
<type>* <name of function> (<types of parameter>)
• Function pointer: pointers to functions
<type> (*<name of function>) (<types of parameter>)

int func (int a, int b) int main(void)


{ {
printf("\n a = %d\n",a); // Function pointer
printf("\n b = %d\n",b); int(*fptr)(int,int);
// Assign address to
return 0; // function pointer
} fptr = func;
func(2,3);
fptr(2,3);

return 0;
}
33
void pointer
• void pointer: a special pointer that has no associated
data type with it
• Can hold address of any type and can be typcasted to any type.
• Generic programming
• Declaration: void *<name of pointer>;
• The void pointer cannot be dereferenced directly
• The void pointer must first be explicitly cast to another pointer type
before it is dereferenced.
#include <stdio.h>
int main()
{
int a = 10;
void *ptr = &a;
printf("%d", *(int *)ptr);
return 0;
}
34
Dynamic Memory Allocation
• A typical memory
representation of C program
consists of following
sections.
1. Text segment: code segment
2. Initialized data segment
3. Uninitialized data segment
4. Stack
5. Heap: the segment where
dynamic memory allocation
usually takes place

35
Dynamic Memory Allocation
• void * malloc( size_t size );
• Allocates requested size of bytes and returns a pointer to first byte
of allocated space
• Doesn’t initialize the allocated memory
• Asigment: ptr = (cast-type*) malloc(byte-size)
• void * calloc( size_t num, size_t size );
• Allocates space for an array elements, initializes to zero and then
returns a pointer to memory
• Initializes the allocates memory block to zero
• Asigment: ptr = (cast-type*)calloc(n, element-size);
• Equivalent:
ptr = malloc(size);
memset(ptr, 0, size);

36
Dynamic Memory Allocation
• void *realloc(void *ptr, size_t size);
• Deallocates the old object pointed to by ptr and returns a pointer to
a new object that has the size specified by size
• ptr = realloc(ptr, newsize);
• void free(void *ptr);
• Deallocate the previously allocated space
• Memory Leak
• Create a memory in heap and forget to delete it
• To avoid memory leaks, memory allocated on heap should always
be freed when no longer needed
• valgrind: suite of tools for debugging and profiling
programs.
$ valgrind –leak-check=full <program>
37
Structure
• Structure is a collection of variables under a single name.
Variables can be of any type: int, float, char etc.
• Declaring a Structure:

38
Using structure variable
• Declare structure variable?
int a;
• This is similar to variable declaration.
struct Customer John;
• Example
• Access structure members: use the dot operator
<structure variable name>.<member name>
• Access to members of a pointer to the variable structure:
using operators →
<structure variable name> -> <member name>

39
Example
struct student{
int id;
int score;
};

int main()
{
int i;
struct student students[5];
for(i=0; i<5; i++){
students[i].id = i;
students[i].score = i;
}
for(i=0;i<5;i++){
printf("student id:%d, score:%d\n",
students[i].id, students[i].score);
}
return 0;
}
40
Structure and Pointer

struct student st; sp


struct student *sp;
sp = &st;
sp->id = 7000123; st
(*sp).score = 23; id 7000123
score 23

printf(“%d\n”, sp->score);

41
Link list
• Store a pointer to the next structure in the structure
struct student {
int id;
int score;
struct student *next;
}
• Warning : allocate memory before use and release
memory after use

*top

42
I/O function

• All I/O calls ultimately


go to the kernel App #2
• I/O library helps with App
buffering, formatting, #1 std. I/O
interpreting (esp. text
strings & conversions) Library

Kernel

43
Input function (include in stdio.h)
• Functions
• printf( ) • getc( )
• Print formatted data to stdout • Character read from standard
• fprintf( ) input
• Write formatted output to stream • putc( )

• gets( ) • Export one character to


standard output
• Read one line from standard
input • Deprecated functions
• NEVER EVER USE THIS! • scanf( )
• fgets( ) • Read formatted data from stdin
• Get string from stream, a • fscanf( )
newline character • Read formatted data from
makes fgets stop reading stream
• USE THIS INSTEAD

44
Input function (include in unistd.h)
• Function
• read()
• Argument : number of bytes read and target
• write()
• Argument : the number of bytes to write to output
• open()
• close()

45
open()/read()/write()/close()
#include <fcntl.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#define BUFSIZE 1024

int main()
{
char buf[BUFSIZE];
int fd;
int nbyte;
fd = open(“test.txt”, O_RDONLY, 0);
while((nbyte = read(fd, buf, BUFSIZE)) > 0) {
write(1, buf, nbyte);
}
close(fd);

return 0;
}
46
File handling functions
• fopen(char *filename, char *mode)
• r,w,a,r+,w+,a+
• fgets(char *s,int length,FILE *fd)
• fgetc(FILE *fd)
• fclose(FILE *fd)

47
Example
#include <stdio.h>

int main(int argc, char *argv[])


{
FILE *fp;
char buf[1024];
int c;
fp = fopen(argv[1],"r");
while((fgets(buf, sizeof(buf),fp)) != NULL){
fputs(buf,stdout);
}
fclose(fp);

return 0;
}

48

You might also like