KEMBAR78
10.1 Networking Sockets C | PDF | Network Socket | Computer Network
0% found this document useful (0 votes)
6 views33 pages

10.1 Networking Sockets C

The document provides an overview of networking concepts, focusing on socket programming and the networking stack, which organizes responsibilities into layers such as Application, Transport, IP, Link, and Physical layers. It discusses the types of sockets (Stream and Datagram), key system calls for socket operations, and the differences between TCP and UDP protocols. Additionally, it includes examples of socket call sequences for both TCP and UDP communication.

Uploaded by

akaaljot.mathoda
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)
6 views33 pages

10.1 Networking Sockets C

The document provides an overview of networking concepts, focusing on socket programming and the networking stack, which organizes responsibilities into layers such as Application, Transport, IP, Link, and Physical layers. It discusses the types of sockets (Stream and Datagram), key system calls for socket operations, and the differences between TCP and UDP protocols. Additionally, it includes examples of socket call sequences for both TCP and UDP communication.

Uploaded by

akaaljot.mathoda
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/ 33

Networking

Sockets

25-03-16 CMPT 201 Slides 10.1 © Dr. B. Fraser 1


Topics


How does software do something complicated
like networking? Layers!
>
-
Stream Sockets (For)
TCP

What are the two types of sockets? Datagram

What syscalls can we use to work with sockets? (ForUDP)
2 sochet
g
.

aucht
connue 2 )
loses
Me

25-03-16 2
Networking

Programs can communicate with each other via a network.
-
– Can be across a network (wifi, wired, ...)
-

– Can be on the same computer!


-

More Resources
– Beej's Guide to Network Programming
https://beej.us/guide/bgnet/ is popular.
– The Linux Programming Interface (our recommended text) Me

is also great.

25-03-16 3
Basics of the Networking Stack

25-03-16 4
Networking Stack

Stack
– .. software uses a network stack to
organize responsibilities into layers
– Each layer provides a service to the layer
above it.

-
Application
-
Transport

IP -

-
Link (MAC)
-
Phy

25-03-16 5
Physical Layer
It converts

Phy (Physical) Layer: - binary data

.. Does Hardwar Control into electrical


,

generates and receives signals. optical or radio


Handles
voltage
luels,
&
– Need to know how to signals that
timing
signal physically send and receive data. can be transmitted
modulation ~
– Focuses on voltage and signalling. through
Application physical

Analogy:
Transport Amazon package delivery: media
.. need
o & driver
car a
IP
2 G .
ethrnet Cables (Wire)
Link (MAC)
·

Metrical signals transmitted our twisted-pair Katiea


Cables
Phy WiFi (wireless
Involves radio Frequency signalling
25-03-16 Fiber optic 6
Link Layer
Man Addres
A
is used
to ●
Link (MAC) Layer:
identify a device
.. Does Local network addressing &
Routing
within a local – This is only for a (small area) local network.
network
.

– E.g., wired or wireless local network.


– LAN = Local Area Network
Application

Link layer has MAC addresses for addressing.
– MAC =.. Medium Access control
Transport MAC address look like: -
05:35:5a:30:f9:05
IP

Analogy: Amazon package delivery: X
– need an address and routes 6
bytes
Link (MAC) (how to get there). or
48 bits
Phy

25-03-16 7
IP (Network) Layer
It ensures
data can travel
-● IP ("Network") Layer:
.. Does inter network addressing
between different I routing
networks , typically across – IP =.. Internet Protocol
the network

What if you want to connect a wired local
network with a wireless local network?
– Still need addressing and routing but it needs
Application
to be something common for both wired and
Transport wireless.

IP

.. This layer uses IP addresses for addressing
– IP addresses look like: 192.168.7.53 > 4
-

bytes
Link (MAC) 32 bits
Amazon Package Delivery
Phy IP address is more like the address used
to
identify locations in
diff neighborhoods.
25-03-16 8
Transport Layer

Transport Layer:
.. Can do packet tracking /Petransmission

Imagine sending/receiving lots of packages:
3 problems can occur:
– .. packagesan be lost
Think car crash; or human errors like losing a
Application package in a warehouse.
Transport
– .. Packages can arriv out of order
They may be delivered by different trucks via
IP different routes.
Link (MAC)
– .. Packages can the duplicated
If the sender mistakenly thinks the package is
Phy lost and re-sends.
This is done using ACKS & Sequence

25-03-16 numbers 9
Transport Layer (cont)
A connection must

we establishich ●
Some applications require an in-order reliable
before data transmissionbyte stream.

begins .
~ ●
Need a way to control these things:
– .. TCP (TransmissionControl Protocol)
provides protection against these things:
-

.. No loss no out of order no Duplication


, ,

Application – .. UDP (User Datagram Protocol)


Transport does not provide any protection! > without
-
-

Raw datagrams = packets. establishing


a

IP connection Useful
Port Number
.

Link (MAC) – Use a socket port number to identify


~
.. ther on computer , which application)
Phy to send a packet
– E.g., port 80, or 443
25-03-16 10
Application Layer

Application Layer:
.. What theapplication is doing.
– Often features a well-known protocol such as:
HTTP and FTP.
The Application Layer dictates what the application is doing in terms of network communication.
For example, when a user requests a webpage, the web browser sends HTTP requests, and the server
sends back HTML content over HTTP.
Application

Transport
Amazon Package Delivery
This is like the service that the customer
IP
.
requests 2g Placing an order
Link (MAC)

Phy

25-03-16 11
ABCD Spot the Address

Which of the following is ___________?
1) an IP Address
2) a MAC Address
3) Port Number

37 a) 8001
2) b) 19:02:16:08:07:01 Glytes
17 c) 153.10.23.103 4 bytes
d) 0xF532 5E85 0005 235F

25-03-16 12
Socket Interface

25-03-16 13
Socket Syscalls

~●
An application can use a socket to communicate with another
process (local or remote)


There are five key syscalls
– socket()
– bind()
– listen()
– accept()
– connect()

25-03-16 14
socket()
int socket(int domain, int type, int protocol)
– .. Returns filedescriptor
a

– Functions to send/receive

socket-specific calls: send(), recv(), sendto(), recvfrom()
-


file I/O calls: read(), write()
-


int domain

– Specifies what protocol is used. What is a protocol?
Specifies

.. It
defines a set
of rules that Entity
an needs
communication
follow to communicats with anotherrntity
to
domain –
Domain examples using the same rules .

whether
comm happens

AF_UNIX: Local communication (this computer)
on local maching ●
AF_INET: IPv4 Internet protocols
or our network

AF_INET6: IPv6 Internet protocols
25-03-16 15
socket() cont It return a
file
- descriptor
int socket(int domain, int type, int protocol)

int type
– SOCK_STREAM: TCP
.. secured
, reliable , I way ,
connectionbased dyt stream

Connection-based / connection-oriented: will explain later
-
handshake
– SOCK_DGRAM: UDP
.. datagrams I connectionless unreliable packets of
, a mass
length)
Connectionless: will explain later. T

making it

but

int protocol faster
– -
Always 0 for us; not used for AF_UNIX, AF_INET, and less
reliabl
AF_INET6. than
TCP -

– Some domains allow different protocols.

25-03-16 16
Stream Socket Sequence (TCP)
This
function Passive Socket creates a Active Socket
blocks the Server
(Server) (Client)
server
tolisten
until a connection socket
- incoming
connections

-
request is
light
socket() for
made by
bind() > socket is bound to a
.. Blocking
-

waits for listen() - specific port I address


> server connection requests
accept() lugins to listen for
.
socket
connection
attempt
2 socket() > client creats
-
a

connect() sochet
X
accept() client cornets to the

returns on server ,
specifying the
new read() write() server's address &
write() read() port

3
connection
Both the server
& client
these
read() write()
uses
functions to
send & receive data over
write() read() the
Established Top
connection

they can continuously


exchange data until
close() close() communication s

complete
25-03-16 ↓ 17

After communication
rnds

Both Client & Serves closether sockets


to release
using these soches resources
TCP Explanation: bind()

socket() creates a socket.

bind().. binds the socket to an address
– Uses a generic address struct.
address
struct sockaddr { define
sa_family_t sa_family; -> family
such as

char sa_data[14]; AEINET for IPrY


// size varies.
-
AF INET ING
// bind() given struct size.
-

for
holds the actual
address data
– Different protocols use different structs
(with different-yet-similar names, and different fields).

25-03-16 18
TCP Explanation: listen(), accept()

listen().. marks the socket as passive
– i.e., it's used to wait for a connection to come (a server).
– By default, a socket is active.
This allows

accept().. accepts a new connection the server
to

- handle multiple
– Returns a new socket to use for the new connection. connections
concurrently
– The original socket is only used to accept new connections. ruch with


connect().. Client connects to a passive sochet its own

sochet
– "connection-oriented" means we establish a connection first.

25-03-16 19
ABCD TCP Call Sequence


Which of the following is the most likely sequence of calls for
a TCP server?

a)
-
b) c) d)

socket() socket() socket() socket()


bind() bind() bind() bind()
listen() listen() listen() write()
read() accept() accept() listen()
accept() read() write() accept()
write() write() read() read()
close() close() close() close()

25-03-16 20
Datagram Socket Sequence (UDP)
Passive Socket Active Socket
waits
(Server) for (Client)


-

socket() ecoming
. The
messages
.. Beaching bind() sever blocks while
waits for recvfrom() socket()
It waits for messages
message a client
arriv from
arrival to

I returns a sendto() > sends a


-

message along recvfrom() message to


with the sendto() The serve
client's address recvfrom()
sendto() using the
information recvfrom() socket
sendto()

close() close()

25-03-16 21
UDP Explanation

"connectionless" means
.. we don't establish a connection frist
– It is like an SMS message that is received one-off
– Each time we receive a message we are told who sent it.

UDP has no active or passive sockets
-
– sendto() needs to specify the receiver's address every time.
-
– recvfrom() tells you who sent it.
-

25-03-16 22
ABCD UDP Call Sequence


Which of the following is the most likely sequence of calls for
a UDP server?
>

a) b) c) -
d)

socket() socket() socket() socket()


bind() bind() bind() bind()
sendto() X listen()X read() recvfrom()
recvfrom() sendto() write()Z file
descriptors sendto()
not
close() close() close() suitable close()
↓ for upP
because they
servr should use datgrams

la waiting for
messages first before responding.
25-03-16 23
ABCD: Who’s call is it?


Which of the options on the right is most likely to use all of
the following calls (not in order):

a) UDP Client
connect() b) UDP Server
close()
read()
-
c) TCP Client
socket() d) TCP Server
write()

25-03-16 24
ABCD: Who’s call is it?


Which of the options on the right is most likely to use all of
the following calls (not in order):

a) UDP Client
bind()
close()
- b) UDP Server
recvfrom()
c) TCP Client
sendto() d) TCP Server
socket()

25-03-16 25
ABCD: Who’s call is it?


Which of the options on the right is most likely to use all of
the following calls (not in order):

accept() a) UDP Client


bind() b) UDP Server
close()
listen()
c) TCP Client
read() -
d) TCP Server
socket()
write()

25-03-16 26
TCP Activity

Create two TCP programs: server and client.
– Implement the socket sequence using AF_UNIX.
(Local machine)
– The client should be able to send messages typed on the
terminal to the server.
– The server should be able to print out the messages.
– man unix for detailed info for AF_UNIX.
– An AF_UNIX address uses struct sockaddr_un:
struct sockaddr_un {
sa_family_t sun_family; /* AF_UNIX */
char sun_path[108]; /* Pathname = “tmp” */
};

25-03-16 27
#include <errno.h>
#include <stdio.h> data
for reading
#include <stdlib.h>
#include <string.h> to be used
#include
#include
<sys/socket.h>
<sys/un.h> >
-
Defines the leuffer Size
path of sorpet
#include <unistd.h>
> the sour can hold in
connections
-

of pending
#define BUF_SIZE 64
#define MY_SOCK_PATH "tmp">
-
maximum no
acce
#define LISTEN_BACKLOG 32

Y
#define handle_error(msg)
\ mus not
a function
{
do
to hander errors
\ Entire
puts the
code in place of the error
perror(msg);
\
exit(EXIT_FAILURE);
\
} while (0)

int main() {

int sfd = socket(AF_UNIX, SOCK_STREAM, 0);


I Removing any existingsonet file
if (sfd == -1)
handle_error("socket");
with zirs
>
- memset is used to fill the memory
if (remove(MY_SOCK_PATH) == -1 && Itfills
don't then
errno != ENOENT) // No such file or directory If
because we

values which
handle_error("remove"); them with garbage
struct sockaddr_un addr;
memset(&addr, 0, sizeof(struct sockaddr_un));
an cuse
lugs & also some

addr.sun_family = AF_UNIX; system calls expect zeroed


strncpy(addr.sun_path, MY_SOCK_PATH, sizeof(addr.sun_path) -
1); memory
if (bind(sfd, (struct sockaddr *)&addr, sizeof(struct
sockaddr_un)) == -1)
handle_error("bind");

the connection
if (listen(sfd, LISTEN_BACKLOG) == -1)
handle_error("listen"); >
-
Rads data from
client through
for (;;) {
int cfd = accept(sfd, NULL, NULL);
if (cfd == -1)
handle_error("accept");

char buf[BUF_SIZE];
ssize_t num_read;
while ((num_read = read(cfd, buf, BUF_SIZE)) > 0) {
if (write(STDOUT_FILENO, buf, num_read) != num_read)
handle_error("write");
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

#define MY_SOCK_PATH "tmp"


#define BUF_SIZE 64
MACRO To handle Borrow
#define handle_error(msg)
do {
& \
\
perror(msg); \
exit(EXIT_FAILURE); \
} while (0)

int main() {

int sfd = socket(AF_UNIX, SOCK_STREAM, 0);


if (sfd == -1)
handle_error("socket");

struct sockaddr_un addr; > connut to


-

memset(&addr, 0, sizeof(struct sockaddr_un));


server
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, MY_SOCK_PATH, sizeof(addr.sun_path) - 1);

if (connect(sfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -1)


handle_error("connect");

char buf[BUF_SIZE];
ssize_t num_read;
while ((num_read = read(STDIN_FILENO, buf, BUF_SIZE)) > 1)
if (write(sfd, buf, num_read) != num_read)
handle_error("write");

if (num_read == -1)
handle_error("read");

exit(EXIT_SUCCESS);
}
UDP Activity

Create two UDP programs: server and client.
– Implement the socket sequence using AF_UNIX.
(Local machine)
– The client should be able to send messages typed on the
terminal to the server.
– The server should be able to print out the messages.
– man unix for detailed info for AF_UNIX.
– An AF_UNIX address uses struct sockaddr_un:
struct sockaddr_un {
sa_family_t sun_family; /* AF_UNIX */
char sun_path[108]; /* Pathname = “tmp” */
};

25-03-16 28
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

#define BUF_SIZE 64
#define MY_SOCK_PATH "tmp"
#define LISTEN_BACKLOG 32

#define handle_error(msg) \
do { \
perror(msg); \
exit(EXIT_FAILURE); \
} while (0)

int main() {
int sfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sfd == -1)
handle_error("socket");

if (remove(MY_SOCK_PATH) == -1 &&
errno != ENOENT) // No such file or directory
handle_error("remove");

struct sockaddr_un addr;


socklen_t len = sizeof(struct sockaddr_un);

memset(&addr, 0, sizeof(struct sockaddr_un));


addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, MY_SOCK_PATH, sizeof(addr.sun_path) - 1);

if (bind(sfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -1)


handle_error("bind");

for (;;) {
char buf[BUF_SIZE];
int num_read = recvfrom(sfd, buf, BUF_SIZE, 0, NULL, &len);
if (write(STDOUT_FILENO, buf, num_read) != num_read)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

#define MY_SOCK_PATH "tmp"


#define BUF_SIZE 64

#define handle_error(msg) \
do { \
perror(msg); \
exit(EXIT_FAILURE); \
} while (0)

int main() {
int sfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sfd == -1)
handle_error("socket");

struct sockaddr_un addr;


memset(&addr, 0, sizeof(struct sockaddr_un));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, MY_SOCK_PATH, sizeof(addr.sun_path) - 1);

ssize_t num_read;
char buf[BUF_SIZE];

while ((num_read = read(STDIN_FILENO, buf, BUF_SIZE)) > 1)


if (sendto(sfd, buf, num_read, 0, (struct sockaddr *)&addr,
sizeof(struct sockaddr_un)) != num_read)
handle_error("sendto");

exit(EXIT_SUCCESS);
Summary

Network Stack has layers (bottom-up)
– phy, link, IP, transport, application

Socket: Connect to communicate across network.

TCP:
– Connection-oriented; in-order delivery.
– Server:
socket(), bind(), listen(), accept(), read(), write()... close()
– Client: socket(), connect(), write(), read(), ... close()

UDP:
– Connectionless
– Server: socket(), bind(), recvfrom(), sendto(), ... close()
– Client: socket(), sendto(), recvfrom(), close()

25-03-16 29

You might also like