The source code in the teaching material from Touge has been provided in network.zip. If you need the source code, please see the end of the article.
SQLite Database Installation
# ================1. Install SQLite Database=============
# The laboratory computer has already installed it, no need to install again
# sudo apt install sqlite3
# sudo apt install libsqlite3-dev
Compiling SQLite Application
# ================2. Compiling SQLite Application============
# This code is in the teaching material from Touge in network.zip. Replace the following content
# with your actual source code path.
cd /tmp/sqlite/
gcc ./sqlite_test.c -lsqlite3 -o ./sqlite_test
./sqlite_test
SQLite Database Command Practice
# ================3. SQLite Database Command Practice===========
# The test database is in the teaching material from Touge in network.zip. In
# /sqlite/test.db is the database file. Replace the following with the actual database
# path.
sqlite3 /tmp/sqlite/test.db
# Execute the following in the sqlite database console.
.database
.tables
.schema
dump
# Enter the following command to exit.
.quit
Compiling and Running TCP Application
# ================3-1. Compiling and Running TCP Application============
# This code is in the teaching material from Touge in network.zip. Replace the following content
# with your actual source code path.
cd /tmp/tcpdemo/make
./server 127.0.0.1 2000
# Open another terminal and execute the following code.
cd /tmp/tcpdemo/
./client 127.0.0.1 2000
# Then in the new window (the one executing ./client), press Ctrl+C, it will automatically
# close ./server and display a successful closure message, otherwise it will not.
Compiling and Running UDP Application
# ================3-2. Compiling and Running UDP Application============
# This code is in the teaching material from Touge in network.zip. Replace the following content
# with your actual source code path.
cd /tmp/udpdemo/make
./server 127.0.0.1 2000
# Open another terminal and execute the following code.
cd /tmp/udpdemo/
./client 127.0.0.1 2000
# In this case, regardless of which window you press Ctrl+C, the other window will not respond, this is determined
# by the transmission characteristics of UDP.
sqlite_test.c
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
// Database file name
const char* DB_FILE = "example.db";
// Callback function for processing results after executing query sql statements
int selectCallback(void* data, int argc, char** argv, char** azColName) {
int i;
for (i = 0; i < argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
// Initialize database connection
sqlite3* initDatabase() {
sqlite3* db;
int rc = sqlite3_open(DB_FILE, &db);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return NULL;
}
return db;
}
// Close database connection
void closeDatabase(sqlite3* db) {
if (db) {
sqlite3_close(db);
}
}
// Create table
void createTable(sqlite3* db) {
char* errMsg;
const char* createSql = "CREATE TABLE IF NOT EXISTS students (id INT PRIMARY KEY, name TEXT, age INT);";
int rc = sqlite3_exec(db, createSql, NULL, 0, &errMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot create table: %s\n", errMsg);
sqlite3_free(errMsg);
} else {
printf("Table created successfully\n");
}
}
// Insert data
void insertData(sqlite3* db, int id, const char* name, int age) {
char insertSql[100];
snprintf(insertSql, sizeof(insertSql), "INSERT INTO students (id, name, age) VALUES (%d, '%s', %d);", id, name, age);
char* errMsg;
int rc = sqlite3_exec(db, insertSql, NULL, 0, &errMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot insert data: %s\n", errMsg);
sqlite3_free(errMsg);
} else {
printf("Data inserted successfully\n");
}
}
// Update data
void updateData(sqlite3* db, int id, const char* name, int age) {
char updateSql[100];
snprintf(updateSql, sizeof(updateSql), "UPDATE students SET name = '%s', age = %d WHERE id = %d;", name, age, id);
char* errMsg;
int rc = sqlite3_exec(db, updateSql, NULL, 0, &errMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot update data: %s\n", errMsg);
sqlite3_free(errMsg);
} else {
printf("Data updated successfully\n");
}
}
// Delete data
void deleteData(sqlite3* db, int id) {
char deleteSql[100];
snprintf(deleteSql, sizeof(deleteSql), "DELETE FROM students WHERE id = %d;", id);
char* errMsg;
int rc = sqlite3_exec(db, deleteSql, NULL, 0, &errMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot delete data: %s\n", errMsg);
sqlite3_free(errMsg);
} else {
printf("Data deleted successfully\n");
}
}
// Query data
void selectData(sqlite3* db) {
char* errMsg;
const char* selectSql = "SELECT * FROM students;";
int rc = sqlite3_exec(db, selectSql, selectCallback, 0, &errMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot query data: %s\n", errMsg);
sqlite3_free(errMsg);
}
}
int main() {
sqlite3* db = initDatabase();
if (db) {
createTable(db);
insertData(db, 1, "Zhang San", 20);
insertData(db, 2, "Li Si", 22);
insertData(db, 3, "Wang Wu", 25);
selectData(db);
updateData(db, 1, "Zhao Liu", 23);
selectData(db);
deleteData(db, 3);
selectData(db);
closeDatabase(db);
}
return 0;
}
sqlite.c
/***sqlite.c*****/
#include<stdio.h>
#include<sqlite3.h>
int main(){ sqlite3 *db=NULL; int rc; char *Errormsg; int row; int col; char **Result; int i=0; int j=0; rc =sqlite3_open("test.db",&db); if(rc) {fprintf(stderr,"cant,t open:%s\n",sqlite3_errmsg(db)); sqlite3_close(db); return 1; } else {printf("open successly!\n");} char *sql="create table people(ID integer primary key,name varchar(10),age integer,num varchar(18))"; sqlite3_exec(db,sql,0,0,&Errormsg); sql="insert into people values(1,'LiMing',20,'362302198901010214')"; sqlite3_exec(db,sql,0,0,&Errormsg); sql="insert into people values(2,'LiSi',21,'362302199005010254')"; sqlite3_exec(db,sql,0,0,&Errormsg); sql="insert into people values(3,'WangWu',20,'362302198905050954')"; sqlite3_exec(db,sql,0,0,&Errormsg); sql="select * from people"; sqlite3_get_table(db,sql,&Result,&row,&col,&Errormsg); printf("row=%d column=%d\n\n",row,col); for(i=0;i<row+1;i++) { for(j=0;j<col;j++) {printf("%s\t",Result[j+i*col]);} printf("\n"); } sqlite3_free(Errormsg); sqlite3_free_table(Result); sqlite3_close(db); return 0;}
tcpdemo/server.c
//TCP Network Programming Server
#include <stdio.h> //printf
#include <arpa/inet.h> //inet_addr htons
#include <sys/types.h>
#include <sys/socket.h> //socket bind listen accept connect
#include <netinet/in.h> //sockaddr_in
#include <stdlib.h> //exit
#include <unistd.h> //close
#include <string.h> //strcat
#define N 128
#define errlog(errmsg) do{perror(errmsg);
printf("%s-->%s-->%d\n", __FILE__, __func__, __LINE__);
exit(1);
}while(0)
int main(int argc, const char *argv[]){ int sockfd, acceptfd; struct sockaddr_in serveraddr, clientaddr; socklen_t addrlen = sizeof(struct sockaddr); char buf[N] = {0};
if(argc < 3) { printf("argument is too few\n"); exit(1); }
// Step 1: Create a socket if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { errlog("fail to socket"); }
// Step 2: Fill in the server network information structure //inet_addr: converts dotted-decimal IP address to network-recognized //htons: converts host byte order to network byte order //atoi: converts numeric string to integer data serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = inet_addr(argv[1]); serveraddr.sin_port = htons(atoi(argv[2]));
// Step 3: Bind the socket to the network information structure if(bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) { errlog("fail to bind"); }
// Step 4: Set the socket to listening state if(listen(sockfd, 10) < 0) { errlog("fail to listen"); }
// Step 5: Block and wait for client connection requests if((acceptfd = accept(sockfd, (struct sockaddr *)&clientaddr, &addrlen)) < 0) { errlog("fail to accept"); }
printf("%s ---> %d\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); while(1) { if(recv(acceptfd, buf, N, 0) <= 0) { errlog("fail to recv"); }
if(strncmp(buf, "quit", 4) == 0) { break; } else { printf("client >>> %s\n", buf);
strcat(buf, " *_*");
if(send(acceptfd, buf, N, 0) < 0) { errlog("fail to send"); } } }
close(acceptfd); close(sockfd);
return 0;}
tcpdemo/client.c
//TCP Network Programming Client
#include <stdio.h> //printf
#include <arpa/inet.h> //inet_addr htons
#include <sys/types.h>
#include <sys/socket.h> //socket bind listen accept connect
#include <netinet/in.h> //sockaddr_in
#include <stdlib.h> //exit
#include <unistd.h> //close
#include <string.h> //strcat
#define N 128
#define errlog(errmsg) do{perror(errmsg);
printf("%s-->%s-->%d\n", __FILE__, __func__, __LINE__);
exit(1);
}while(0)
int main(int argc, const char *argv[]){ int sockfd; struct sockaddr_in serveraddr; socklen_t addrlen = sizeof(struct sockaddr); char buf[N] = {0};
if(argc < 3) { printf("argument is too few\n"); exit(1); }
// Step 1: Create a socket if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { errlog("fail to socket"); }
// Step 2: Fill in the server network information structure //inet_addr: converts dotted-decimal IP address to network-recognized //htons: converts host byte order to network byte order //atoi: converts numeric string to integer data serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = inet_addr(argv[1]); serveraddr.sin_port = htons(atoi(argv[2]));
// Step 3: Send client connection request if(connect(sockfd, (struct sockaddr *)&serveraddr, addrlen) < 0) { errlog("fail to connect"); }
while(1) { fgets(buf, N, stdin); buf[strlen(buf) - 1] = '\0';
if(send(sockfd, buf, N, 0) < 0) { errlog("fail to send"); }
if(strncmp(buf, "quit", 4) == 0) { break; } else { if(recv(sockfd, buf, N, 0) < 0) { errlog("fail to recv"); } printf("server >>> %s\n", buf); } } close(sockfd);
return 0;}
tcpdemo/Makefile
EXEC1 = server
EXEC2 = client
OBJS1 = server.o
OBJS2 = client.o
HEADERS =
CC = gcc
INC =
CFLAGS = ${INC} -g
all:${EXEC1} ${EXEC2}
${EXEC1} : ${OBJS1} ${CC} ${CFLAGS} ${LDFLAGS} -o $@ ${OBJS1}
${OBJS1} : ${HEADERS}
${EXEC2} : ${OBJS2} ${CC} ${CFLAGS} ${LDFLAGS} -o $@ ${OBJS2}
${OBJS2} : ${HEADERS}
.PHONY : clean
clean : -rm -f ${OBJS1} ${EXEC1} -rm -f ${OBJS2} ${EXEC2}
udpdemo/server.c
#include<stdlib.h>
#include<stdio.h>
#include<sys/socket.h>
#include<netdb.h>
#include<string.h>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
void PrintAPI(char * str){ fprintf(stderr," %s usage for communication:\n", str); fprintf(stderr,"%s IP Address [port]\n", str);}
int main(int argc,char** argv){ struct sockaddr_in StSever,StClient; int fd,len,port,opt; int Send_Num,Recv_Num; char SendBuf[1024]; char RecvBuf[1024];
int addr_len = sizeof(struct sockaddr_in); if (3==argc) { port = atoi(argv[2]); }else{ PrintAPI(argv[0]); exit(1);}
memset(SendBuf,0,1024); memset(RecvBuf,0,1024); opt=SO_REUSEADDR; if (-1==(fd=socket(AF_INET,SOCK_DGRAM,0))){ perror("create socket error\n"); exit(1); } memset(&StSever,0,sizeof(struct sockaddr_in)); StSever.sin_family = AF_INET; StSever.sin_addr.s_addr = htonl(INADDR_ANY); StSever.sin_port = htons(port); if (-1==bind(fd,(struct sockaddr *)&StSever,sizeof(struct sockaddr))){ perror("bind error\n"); exit(1); } while (1) { printf(" server waits for client's message :\n"); if (0>(Recv_Num = recvfrom(fd,RecvBuf,sizeof(RecvBuf),0,(struct sockaddr *)&StClient,&addr_len))) { perror("recv error\n"); continue; } RecvBuf[Recv_Num]='\0'; printf ("the message from the client is: %s\n",RecvBuf); if (0==strncmp(RecvBuf,"quit",4)){ perror("the client break the server process\n"); close(fd); break; } Send_Num = sprintf(SendBuf,"The message from client is %s\n",RecvBuf); sendto(fd,SendBuf,sizeof(SendBuf),0,(struct sockaddr *)&StClient,sizeof(StClient)); continue; } close(fd); return 0;}
udpdemo/client.c
#include<stdlib.h>
#include<stdio.h>
#include<sys/socket.h>
#include<netdb.h>
#include<string.h>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define PORT 8848
void PrintAPI(char * str){ fprintf(stderr," %s usage for communication:\n", str); fprintf(stderr,"%s IP Address [port]\n", str);}
int main(int argc,char** argv){ struct sockaddr_in StSever; int ret,len,port,fd,Send_Num,Recv_Num; char SendBuf[1024]; char RecvBuf[1024]; int addr_len = sizeof(struct sockaddr_in);
if (3==argc) { port = atoi(argv[2]); }else{ PrintAPI(argv[0]); exit(1);}
if (-1==(fd=socket(AF_INET,SOCK_DGRAM,0))){ perror("can not create socket\n"); exit(1); } memset(&StSever,0,sizeof(struct sockaddr_in)); StSever.sin_family = AF_INET; StSever.sin_addr.s_addr = inet_addr(argv[1]); StSever.sin_port = htons(port); if (0>(ret=connect(fd,(struct sockaddr*)&StSever,sizeof(struct sockaddr)))){ perror("connect error"); close(fd); exit(1); } while(1){ printf("Please input info to server:\n"); fgets(SendBuf,1024,stdin); if (0>(len=sendto(fd,SendBuf,sizeof(SendBuf),0,(struct sockaddr *)&StSever,sizeof(StSever)))) { perror("send data error\n"); close(fd); exit(1); }
if(strncmp(SendBuf, "quit", 4) == 0) { break; } else { if (0>(len=recvfrom(fd,RecvBuf,sizeof(RecvBuf),0,(struct sockaddr *)&StSever,&addr_len))) { perror("recv data error\n"); close(fd); exit(1); } RecvBuf[len]='\0'; printf("the message from the server is:%s\n",RecvBuf); } } printf("The client is closed \n"); close(fd);}
udpdemo/Makefile
EXEC1 = server
EXEC2 = client
OBJS1 = server.o
OBJS2 = client.o
HEADERS =
CC = gcc
INC =
CFLAGS = ${INC} -g
all:${EXEC1} ${EXEC2}
${EXEC1} : ${OBJS1} ${CC} ${CFLAGS} ${LDFLAGS} -o $@ ${OBJS1}
${OBJS1} : ${HEADERS}
${EXEC2} : ${OBJS2} ${CC} ${CFLAGS} ${LDFLAGS} -o $@ ${OBJS2}
${OBJS2} : ${HEADERS}
.PHONY : clean
clean : -rm -f ${OBJS1} ${EXEC1} -rm -f ${OBJS2} ${EXEC2}