0% found this document useful (0 votes)
72 views42 pages

Unit - V: Application Development

Here are the key points about pthread_detach: - By default, threads created with pthread_create are joinable - meaning the creator thread must call pthread_join to wait for the thread to complete. - pthread_detach detaches the thread from the creator, making it detached. - Detached threads cannot be joined - their resources are reclaimed by the system when the thread exits without needing to join. - Detaching avoids resource leaks if the creator exits without joining detached threads. So in summary, pthread_detach detaches a thread from its creator so the creator does not need to join the thread later to reclaim resources. It makes the thread detached and unable to

Uploaded by

Karthi Keyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views42 pages

Unit - V: Application Development

Here are the key points about pthread_detach: - By default, threads created with pthread_create are joinable - meaning the creator thread must call pthread_join to wait for the thread to complete. - pthread_detach detaches the thread from the creator, making it detached. - Detached threads cannot be joined - their resources are reclaimed by the system when the thread exits without needing to join. - Detaching avoids resource leaks if the creator exits without joining detached threads. So in summary, pthread_detach detaches a thread from its creator so the creator does not need to join the thread later to reclaim resources. It makes the thread detached and unable to

Uploaded by

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

UNIT – V

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

Ether IPv6 TCP TCP Ether IPv4 TCP TCP


hdr hdr hdr data hdr hdr hdr data
type dport type dport
86dd 8888 8000 8888
5
Dual-Stack Kernel at Server 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
returned by IPv4- IPv4-
IPv4 IPv6
accept or mapped mapped
recvfrom
IPv4 IPv6

IPv4 datagram IPv6 datagram

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 datagram IPv6 datagram


7
Interoperability between IPv4 and IPv6
Clients and Servers

IPv4 server IPv6 server IPv4 server IPv6 server


IPv4-only host IPv6-only host dual-stack host dual-stack host
(A only) (AAAA only) (A and AAAA) (A and AAAA)
IPv4 client, IPv4 (no) IPv4 IPv4
IPv4-only host
IPv6 client, (no) IPv6 (no) IPv6
IPv6-only host
IPv4 client, IPv4 (no) IPv4 IPv4
dual-stack host
IPv6 client, IPv4 IPv6 (no*) IPv6
dual-stack host

*: 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

• Problems with fork approach for concurrency


 Expensive
Memory copied from parent to child
All descriptors are duplicated in the child
Can be implemented using copy-on-write (don’t copy until
child needs own copy)
 IPC (Inter-process communication) required to pass
information between parent and child after fork

• Threads can help!!

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

void * func (void *); //function prototype


pthread_t tid; //to hold thread ID

Pthread_create (&tid, NULL, func, NULL);

void * func (void * arg)


{
}
Threads 17
Basic Thread Functions 3/6

• 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

 similar to getpid() for Unix processes

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

• If we pass the address of connfd, what can go wrong?


for ( ; ; ) {
len = addrlen;
connfd = Accept(listenfd, cliaddr, &len);
Pthread_create(&tid, NULL, &doit, &connfd);
}
• A more correct approach would be to allocate space for the
connected descriptor every time before the call to accept
for ( ; ; ) {
len = addrlen;
iptr = Malloc(sizeof(int));
*iptr = Accept(listenfd, cliaddr, &len);
Pthread_create(&tid, NULL, &doit, iptr);
} // source code in threads/tcpserv02.c
Threads 24
Thread Synchronization: Mutex
• How can a thread ensure that access/updates to shared variables
are atomic?
• How can a thread ensure that it is the only thread executing
some critical piece of code?
 Need a mechanism for thread coordination and
synchronization
 semaphores and mutex calls
• Mutex: Mutual Exclusion
 Threads can create a mutex and initialize it. Before entering a
critical region, lock the mutex.
 Unlock the mutex after exiting the critical region
 See examples in threads/example01.c and threads/example02.c
Threads 25
Thread Synchronization: Semaphores
• A mutex allows one thread to enter a critical region
• A semaphore can allow some N threads to enter a critical region
 Used when there is a limited (but more than 1) number of
copies of a shared resource
• Can be dynamically initialized
 Thread calls a semaphore wait function before it enters a
critical region
• Semaphore is a generalization of a mutex

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)

TCP TCP UDP


RAW RAW
port port port

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;

setsockopt (sockfd, IPPROTO_IP, IP_HDRINCL,


&on, sizeof(on);

Can we use bind() with raw sockets?


rare, no concept of port
Can we use connect() with raw sockets?
rare, only foreign ip address 34
Raw Socket Output
• Sending raw socket packets by sendto or sendmsg
– If IP_HDRINCL option not set (i.e. header is not included), the starting address
of the data in sendto() specifies the first byte following the IP header
– If IP_HDRINCL option set, the starting address of data in sendto()
specifies the first byte of the IP header.

• IP Header fields modified on sending by IP_HDRINCL


– IP Checksum Always filled in.
– Source Address Filled in when zero.
– Packet Id Filled in when zero.
– Total Length Always filled in.

• Example: see Steven’s code under ping/send_v4.c,


ping/send_v6.c
35
Raw Socket Input

• Received TCP/UDP packets are NEVER passed to raw sockets. If


needed, link layer is the place.

• Receiving raw packets by recvfrom() or recvmsg()


– Most ICMP packets are passed to all matching ICMP raw sockets except a
few exceptions
• ICMP echo request, timestamp request
– All IGMP packets are passed to all matching raw sockets
– All IP datagrams with a protocol field not processed by the kernel (e.g.
OSPF) are passed to all matching raw sockets

• The entire datagram, including the IP header, is passed to the raw


socket. Fragments are assembled first.

• Example: steven’s code in ping/readloop.c and


ping/proc_v4.c
36
ICMP Format

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

 Non Standard Communications

 No automatic ICMP

 No Raw TCP or UDP

 Must have root (or administrator) privilege


When to use
 When you need to control the IP header
 applications like Ping and Traceroute
 not all fields can be set using the IP APIs
 Network Address Translation
• Firewalls

 When your application requires optimum network speed


 one level above the Link Layer
 if you need reliability, you must build it into your application
Windows and Raw Sockets
 WinSock 2.0 allows windows programmers to build advanced
applications
 Firewalls
• Network Address Translation
• Packet Filtering
• SYN Flood protection
 Security
• IPSec support
• VPN Clients
 Network Administration
• Packet Sniffers/Analyzers
• Pathway Analyzers (ping and traceroute)

You might also like