Beruflich Dokumente
Kultur Dokumente
APPLICATION
DEVELOPMENT
1
Ipv4 and Ipv6 interoperability
• how IPv4 applications and IPv6 applications
can communicate with each other. There are
four combinations of clients and servers using
either IPv4 or IPv6
• when the client and server use different
protocols.
IPv4 and IPv6 Interoperability
• IPv4 client, IPv6 server over dual-stack
server host
• IPv6 client over dual-stack client host, IPv4
server
• IPv6 address macro, function and option
• Source code portability
3
IPv4 Client, IPv6 Server
IPv4 Client, IPv6 Server
over Dual-Stack Server Host
IPv6 IPv4 IPv6 listening IPv6
client client socket bounded server
to 0::0, port 8888
TCP TCP TCP
IPv4-mapped IPv6 address
IPv6 address
IPv6 IPv4 IPv4 IPv6
206.62.226.43 5f1b:df00:ce3e:e200:
data data data 20:800:2b37:6426
link link link
TCP UDP
IPv6 IPv4
address
returned by IPv4- IPv4-
IPv4 IPv6
accept or mapped mapped
recvfrom
IPv4 IPv6
6
Dual-Stack Kernel at Client Side
AF_INET AF_INET
IPv4 sockets SOCK_STREAM SOCK_DGRAM
sockaddr_in sockaddr_in
AF_INET6 AF_INET6
IPv6 sockets SOCK_STREAM SOCK_DGRAM
sockaddr_in6 sockaddr_in6
TCP UDP
IPv6 IPv4
address for
connect or IPv4- IPv4-
IPv4 IPv6
sendto mapped mapped
IPv4 IPv6
*: IPv4-mapped IPv6 address if client chooses A record; no if client chooses AAAA record
Note that most implementations of IPv6 client/server will be on dual-stack hosts. (Second
row and second column may disappear.)
8
IPv6 Address Macro, Function, Option
• IPv6 address testing macros:
– IN6_IS_ADDR_* (e.g. V4MAPPED)
• Protocol independent socket address functions:
– sock_* (e.g. cmp_addr)
• IPv6_ADDRFORM socket option:
– change a socket type between IPv4 and IPv6, by
setsockopt function with IPv6_ADDRFORM
option
9
Source Code Portability
• Automatic program conversion from IPv4
to IPv6 (sockaddr_in, AF_INET, etc) and
#ifdef to use IPv6 when possible
• Deal with socket address structures as
opaque objects:
– remove gethostbyname and gethostbyaddr, use
getaddrinfo and getnameinfo (which use #ifdef
internally)
10
Outline
•Threads
Introduction
Basic Thread Functions
TCP echo client using threads
TCP Echo Server using threads
Thread Synchronization
Threads 11
Introduction 1/4
Threads 12
Introduction 2/4
• Threads
Advantages
Lightweight process
Thread creation can be 10-100 times faster than process
creation
Lower context-switching overhead
All threads within a process share same global memory
POSIX threads standard
Pthreads library
supported by Linux and is portable to most UNIX
platforms
Has been ported to Windows
Threads 13
Introduction 3/4
• Threads
Disadvantages
Global variables are shared between threads
Inadvertent modification of shared variables can be
disastrous (need for concurrency control)
Many library functions are not thread-safe.
Library functions that return pointers to internal static
arrays are not thread safe
To make it thread-safe caller allocates space for the
result and passes that pointer as argument to the function
Lack of robustness: If one thread crashes, the whole
application crashes
Threads 14
Introduction 4/4
• Threads
State
Threads within a process share global data: process
instructions, most data, descriptors, etc, …
File descriptors are shared. If one thread closes a file, all
other threads can’t use the file
Each thread has its own stack and local variables
I/O operations block the calling thread.
Some other functions act on the whole process. For
example, the exit() function terminates the entire process
and all associated threads.
Threads 15
Basic Thread Functions 1/6
• pthread_create function
#include <pthread.h>
int pthread_create (pthread_t * tid, const pthread_attr_t *attr, void
*(*func) (void*), void *arg);
//Returns 0 if OK, positive Exxx value on error
When a program is started, single thread is created (main thread).
Create more threads by calling pthread_create()
pthread_t is often an unsigned int. returns the new thread ID
attr: is the new thread attributes: priority, initial stack size, daemon
thread or not. To get default attributes, pass as NULL
func: address of a function to execute when the thread starts
arg: pointer to argument to function (for multiple arguments,
package into a structure and pass address of structure to function)
Threads 16
Basic Thread Functions 2/6
• pthread_create function
Example
• pthread_join function
#include <pthread.h>
int pthread_join (pthread_t tid, void ** status);
//Returns 0 if OK, positive Exxx value on error
Wait for a given thread to terminate (similar to waitpid() for
Unix processes)
Must specify thread ID (tid) of thread to wait for
If status argument non-null
Return value from thread (pointer to some object) is
pointed to by status
Threads 18
Basic Thread Functions 4/6
• pthread_self function
#include <pthread.h>
pthread_t pthread_self (void);
//Returns thread ID of calling thread
Threads 19
Basic Thread Functions 5/6
• pthread_detach function
#include <pthread.h>
int pthread_detach (pthread_t tid);
//Returns 0 if OK, positive Exxx value on error
A thread is either joinable (default) or detached
When a joinable thread terminates thread ID and exit
status are retained until another thread calls pthread_join
When a detached thread terminates all resources are
released and can not be waited for to terminate
Example : pthread_detach (pthread_self());
Threads 20
Basic Thread Functions 6/6
• pthread_exit function
#include <pthread.h>
void pthread_exit (void * status);
//Does not return to caller
If thread not detached, thread ID and exit status are retained
for a later pthread_join by another thread in the calling
process
Other ways for a thread to terminate
Function that started the thread terminates, with its return value
being the exit status of the thread
main function of process returns or any thread calls exit,. In
such case, process terminates including any threads
Threads 21
TCP Echo Client using Threads
• Recode str_cli function using threads
• Source code in threads/strclithread.c
Can test using threads/tcpcli01.c
tcpcli01.c uses tcp_connect function introduced in section 11.12
Need to pass host name and service
Can also test by threads/tcpcli01_plain.c Pass server’s IP
address
• If server terminates prematurely
Readline function returns 0 and str_cli function terminates
main function terminates calling exit terminate all threads
• Alternative to using global data for threads to share?
See threads/strclithread_args.c, test with
threads/tcpcli01_plain_args.c
Threads 22
TCP Echo Server using Threads 1/2
• One thread per client instead of one child process per client
• Source code in threads/tcpserv01.c
• Uses tcp_listen function introduced in section 11.13
• Main processing loop
for ( ; ; ) {
len = addrlen;
connfd = Accept(listenfd, cliaddr, &len);
Pthread_create(&tid, NULL, &doit, (void *) connfd);
}
The casting (void*) connfd is OK on most Unix
implementations (size of an integer is <= size of a pointer)
Is there an alternative approach?
Threads 23
TCP Echo Server using Threads 2/2
Threads 26
Thread Synchronization: Condition Variables 1/2
• A condition variable is only needed where
A set of threads are using a mutex to provide mutually
exclusive access to some resource
Once a thread acquires the resource, it needs to wait for a
particular condition to occur
• If no condition variables are available
– Some form of busy waiting in which thread repeatedly
acquires the mutex, tests the condition, and then releases the
mutex (wasteful solution)
• A condition variable allows a thread to release a mutex and
block on a condition atomically
Threads 27
Thread Synchronization: Condition Variables 2/2
• Acquire a mutex
• Call pthread_cond_wait specifying both a condition variable and
the mutex being held
• Thread blocks until some other thread signals the variable
• Two forms of signaling
Allow one thread to proceed, even if multiple threads are
waiting on the signaled variable
OS simultaneously unblocks the thread and allows the thread to
reacquire the mutex
Allow all threads that are blocked on the variable to proceed
Blocking on a condition variable does not prevent others from
proceeding through the critical section, another thread can
acquire the mutex
Threads 28
Introduction to Raw Sockets
29
Raw Sockets
30
TCP/IP Stack
67
25 21 23 53 161 69
Bootp
DHCP
TCP UDP
Port # Port #
EGP OSPF
8 89 6 17 Port
address
protocol
1 2
IP
address
frame
type
MAC
address
31
What can raw sockets do?
Bypass TCP/UDP layers
Read and write ICMP and IGMP packets
ping, traceroute, multicast daemon
Read and write IP datagrams with an IP protocol field not
processed by the kernel
OSPF
user process versus kernel
Send and receive your own IP packets with your own IP header
using the IP_HDRINCL socket option
can build and send TCP and UDP packets
testing, hacking
only superuser can create raw socket though
You need to do all protocol processing at user-level
32
ICMP IGMP User TCP User UDP
(ping, etc)
ICMP
echo TCP stack UDP stack
timestamp
port port
17 UDP
6 TCP
1 ICMP
2 IGMP
89 OSPF
33
Creating a Raw Socket
int sockfd;
IPPROTO_ICMP
IPPROTO_IGMP
sockfd = socket(AF_INET, SOCK_RAW, protocol);
const int on = 1;
subtype
39
Ping Program
• Create a raw socket to send/receive ICMP echo request and
echo reply packets
• Install SIGALRM handler to process output
– Sending echo request packets every t seconds
– Build ICMP packets (type, code, checksum, id, seq, sending
timestamp as optional data)
• Enter an infinite loop processing input
– Use recvmsg() to read from the network
– Parse the message and retrieve the ICMP packet
– Print ICMP packet information, e.g., peer IP address, round-trip time
• Source code: Steven’s under ping/
40
Traceroute program
• Create a UDP socket and bind source port
– To send probe packets with increasing TTL
– For each TTL value, use timer to send a probe every three seconds,
and send 3 probes in total
• Create a raw socket to receive ICMP packets
– If timeout, printing “ *”
– If ICMP “port unreachable”, then terminate
– If ICMP “TTL expired”, then printing hostname of the router and
round trip time to the router
• Source code: Steven’s traceroute/
41
Limitations
Loss of Reliability
No ports
No automatic ICMP