PowerPoint Presentation
Lecture 11
Network Programming
Copyright By PowCoder代写 加微信 powcoder
COMP1411: Introduction to Computer Systems
Dr. Xianjin XIA
Department of Computing,
The Hong Kong Polytechnic University
Spring 2022
These slides are only intended to use internally. Do not publish it anywhere without permission.
Acknowledgement: These slides are based on the textbook (Computer Systems: A Programmer’s Perspective) and its slides.
In this lecture, we will study:
basic concepts in computer networking
tools/commands for networking
low-level functions for networking in the C language
but you are not expected to write networking programs yet
More details will be covered in another subject:
COMP2322 Computer Networking
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
A computer is not a closed box
Network interfaces – I/O device for networking
Network interface
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
A computer is not a closed box
Network interfaces – I/O device for networking
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Hardware Organization of a Network Host
register file
system bus
memory bus
controller
controller
Expansion slots
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
A Client-Server Transaction
Many network applications are based on the client-server model:
A server process & multiple client processes
Server manages some resource and provides service to clients
Server activated by request from client
1. Client sends request
3. Server sends response
Note: clients and servers are processes running on hosts
(can be the same or different hosts)
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Computer Networks
A network is a hierarchical system of boxes and wires organized by geographical proximity
SAN (System Area Network) spans cluster or machine room
LAN (Local Area Network) spans a building or campus
WAN (Wide Area Network) spans country or world
An internetwork (internet) is an interconnected set of networks
The Global IP Internet (uppercase “I”) is the most famous example of an internet (lowercase “i”)
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
LANs and internets
An internet (lower case): multiple LANs connected by routers
LAN 1 and LAN 2 might be different and incompatible
(e.g., Ethernet, Fibre Channel, 802.11*, T1-links, DSL, …)
Simplified view of a LAN
A collection of hosts attached to a single wire
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Logical Structure of an internet
Ad hoc interconnection of networks
No particular topology
Send packets from source to destination through networks
Router forms bridge from one network to another
Different packets may take different routes
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
How computers find each other
IP address: To locate a computer in the network
Each network interface has a unique MAC address
hardcoded when the interface hardware is produced
like your HKID
Each computer is assigned an IP address, configurable
like your home address
The MAC address is bind with an IP address when your computer is connected to some network
For your smartphone, at home, you have an IP address; when you connect to the WIFI in Starbucks, you have another IP address
An IP address is a 32-bit integer
128.2.203.179
We focus on IPv4, which uses 32-bit addresses
The new version is IPv6, which uses 128-bit addresses
IP addresses are used by routers to forward data packets
How computers find each other
But when we surf the Internet, we use
www.google.com
www.polyu.edu.hk
www.youtube.com
IP addresses are hard to remember
Computers in the networks can be assigned a domain name
Human-friendly structured string
apollo.comp.polyu.edu.hk 158.132.xxx.xxx
Mapping between domain names and IP addresses are stored on domain name servers, mapping service is provided by these servers
How computers find each other
But I am running my program, chrome, word… on my computer, how does another computer know that “my program”, not chrome, is communicating with it?
Port number
Loosely speaking, a port number is used to uniquely identify a process on the computer
Client socket address
128.2.194.242:51213
Server socket address
208.216.181.15:80
Client host address
128.2.194.242
Server host address
208.216.181.15
How to send bits across incompatible LANs and WANs?
Think of mailing a letter…
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
How to send bits across incompatible LANs and WANs?
Solution: an internet protocol running on hosts and routers
Protocol is a set of rules that governs how hosts and routers should cooperate when they transfer data from network to network
It provides a naming scheme
It defines a uniform format for host addresses
Each host (and router) is assigned at least one of these internet addresses that uniquely identifies it
It provides a delivery mechanism
It defines a standard transfer unit (packet)
Packet consists of header and payload
Header: contains info such as packet size, source and destination addresses
Payload: contains data bits sent from source host
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Transferring internet Data Via Encapsulation
LAN2 frame
internet packet
LAN1 frame
PH: Internet packet header
FH: LAN frame header
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Data packets
Pre-defined data structure containing important information for the data to be transmitted in the network, such as IP addresses, packet length, etc.
The data, usually a specified number of bytes
To transmit large data, trunk them into smaller packets
Other Issues
In the area “computer networking”, we study the following important issues:
How do routers know where to forward frames?
How are routers informed when the network topology changes?
What if packets get lost?
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition
Socket programming
The socket interface
A set of functions that are used in conjunction with the Unix I/O functions to build network applications
Client / Server
Connection
Await connection
request from
next client
open_listenfd
open_clientfd
getaddrinfo
getaddrinfo
Socket address structures
The socket address
From the perspective of the Linux kernel, a socket is an end point for communication
From the perspective of a Linux program, a socket is an open file with a corresponding descriptor
struct sockaddr_in {
uint16_t sin_family; /* Protocol family (always AF_INET) */
uint16_t sin_port; /* Port num in network byte order */
struct in_addr sin_addr; /* IP addr in network byte order */
unsigned char sin_zero[8]; /* Pad to sizeof(struct sockaddr) */
Socket programming example
// Server program
#include
#include
#include
#include
#include
#include
#define PORT 8080
int main(int argc, char *argv[])
int server_fd; // socket file descriptor
struct sockaddr_in address; // socket address
int addrlen = sizeof(address); // length of socket address
int opt = 1;
char buffer[1024] = {0};
int new_socket, valread;
// STEP 1: Creating socket file descriptor
// AF_INET: indicates using 32-bit IP address
// SOCK_STREAM: indicate the socket will be an endpoint for connection
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("socket failed\n");
exit(EXIT_FAILURE);
printf("Server: socket created\n");
Socket programming example
// STEP 2: creating a socket address
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)))
printf("setsockopt\n");
exit(EXIT_FAILURE);
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// The htons function converts a u_short from host to
// TCP/IP network byte order (which is big-endian)
// STEP 3: associate the server’s socket address with the socket descriptor
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0)
printf("bind failed\n");
exit(EXIT_FAILURE);
printf("Server: address binded\n");
Socket programming example
// STEP 4: turn th socket descriptor into a listen descriptor
// Servers are passive entities that wait for connection requests from clients.
// A server calls the listen function to tell the kernel that
// the socket descriptor will be used by a server instead of a client
// the second parameter configures how many incoming requests can be queued
if (listen(server_fd, 1024) < 0)
printf("listen\n");
exit(EXIT_FAILURE);
printf("Server: listening descriptor created\n");
// STEP 5: wait for request from client
// The accept function waits for a connection request
// from a client to arrive on the listening descriptor
// and returns a connected descriptor used to communicate
// with the client using Unix I/O functions
// The listening descriptor serves as an end point for client connection requests
// It is typically created once and exists for the lifetime of the server
// The connected descriptor is the end point of the connection
// that is established between the client and the server.
// It is created each time the server accepts a connection request
// and exists only as long as it takes the server to service a client
// The server blocks at accept() until a request is sent from the client
printf("Server: now I wait for requests\n");
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0)
printf("accept\n");
exit(EXIT_FAILURE);
Socket programming example
// STEP 6: read incoming data
// when program reaches here, the server must have received
// a request from the client
valread = read(new_socket, buffer, 1024);
printf("\n\n\nServer: message received from the client:\n %s\n",buffer);
// STEP 7: send some data to the client
// to demonstrate bi-direction communication
char svmsg[100];
strcpy(svmsg, "This is server speaking\n");
send(new_socket , svmsg , strlen(svmsg) , 0);
printf("Server: message sent\n");
Socket programming example
// Client program
#include
#include
#include
#include
#include
#include
#define PORT 8080
int main(int argc, char *argv[])
struct sockaddr_in serv_addr;
int valread;
char buffer[1024] = {0};
// STEP 1: create a socket on the client side
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("\n Socket creation error \n");
return -1;
printf("Client: socket created\n");
// STEP 2: create socket address
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0)
printf("\nInvalid address/ Address not supported \n");
return -1;
Socket programming example
// STEP 3: using connect to send a request to the server
// The connect function attempts to establish an Internet connection
// with the server at serv_addr
// The connect function blocks until either the connection is
// successfully established or an error occurs
// If successful, the clientfd descriptor is now ready for reading and writing
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
printf("\nConnection Failed \n");
return -1;
printf("Client: connecting server\n");
// STEP 4: send data to the server
char clmsg[100];
strcpy(clmsg, "Hello from client\n");
send(sock, clmsg, strlen(clmsg), 0);
printf("Client: message sent\n");
// STEP 5: read data sent from the server
valread = read(sock, buffer, 1024);
printf("\n\n\nClient: message received from server:\n%s\n", buffer);
/docProps/thumbnail.jpeg
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com