0% found this document useful (0 votes)
8 views19 pages

NP 5

The document covers advanced concepts in network programming, focusing on IPv4 and IPv6 interoperability, threaded servers, and raw sockets. It discusses how servers can handle both IPv4 and IPv6 clients, the creation and management of threads, and the use of mutexes and condition variables for synchronization. Additionally, it includes practical examples such as a TCP echo server, ping, and traceroute programs.

Uploaded by

kandamadhuri
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)
8 views19 pages

NP 5

The document covers advanced concepts in network programming, focusing on IPv4 and IPv6 interoperability, threaded servers, and raw sockets. It discusses how servers can handle both IPv4 and IPv6 clients, the creation and management of threads, and the use of mutexes and condition variables for synchronization. Additionally, it includes practical examples such as a TCP echo server, ping, and traceroute programs.

Uploaded by

kandamadhuri
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/ 19

www.anuupdates.

org
Network Programming – MC9241

NETWORK PROGRAMMING

UNIT V ADVANCED SOCKETS


Ipv4 and Ipv6 interoperability – threaded servers – thread creation and termination – TCP
echo server using threads – Mutexes – condition variables – raw sockets – raw socket
creation – raw socket output – raw socket input – ping program – trace route program.

Ipv4 and Ipv6 interoperability

• Server and client combination


– IPv4 <=> IPv4(most server and client)
– IPv4 <=> IPv6
– IPv6 <=> IPv4
– IPv6 <=> IPv6
• How IPv4 application and IPv6 application can communicate with each other.
• Hosts are running dual stacks, both an IPv4 protocol stack and IPv6 protocol stack.

IPv4 Client , IPv6 Server

• IPv6 dual stack server can handle both IPv4 and IPv6 clients.
• This is done using IPv4-mapped IPv6 address
• server create an IPv6 listening socket that is bound to the IPv6 wildcard address.

1 CCET
www.anuupdates.org
Network Programming – MC9241

IPv6 client, IPv4 server


• IPv4 server start on an IPv4 only host and create an IPv4 listening socket
• IPv6 client start, call gethostbyname. IPv4 mapped IPv6 address is returnedUsing IPv4
datagram.

Converting an IPv4 to IPv6

2 CCET
www.anuupdates.org
Network Programming – MC9241

Int af;
socklen_t clilen;
struct sockaddr_int6 cli; /* IPv6 struct */
struct hostent *ptr;
af = AF_INT6;
Setsockopt (STDIN_FILENO, IPPROTO_IPV6, IPV6_ADDRFORM, &af, sizeof(af));
clilen = sizeof (cli);
Getpeername(0, &cli, &clilen);
ptr = gethostbyaddr (&cli.sin6_addr, 16, AF_INET);

• setsockopt => change the Address format of socket from IPv4 to IPv6.
Return value is AF_INET or AF_INET6
• getpeername =>return an IPv4-mapped IPv6 address

Threaded Servers

Thread
• A thread is not an object
• A thread is a flow of control
• A thread is a series of executed statements
• A thread is a nested sequence of method calls

The Thread Object


• A thread is not an object
• A Thread is an object
void start()
– Creates a new thread and makes it runnable
void run()
– The new thread begins its life inside this method

Runnable Interface
• A helper to the thread object
• The Thread object’s run() method calls the Runnable object’s run() method
• Allows threads to run inside any object, regardless of inheritance

Runnable Example

Talker talker = new Talker();


Thread t = new Thread(talker);
t.start();

3 CCET
www.anuupdates.org
Network Programming – MC9241

---
class Talker implements Runnable {
public void run() {
while (true) {
System.out.println(“yakitty yak”);
}
}
}

Blocking Threads
• When reading from a stream, if input is not available, the thread will block
• Thread is suspended (“blocked”) until I/O is available
• Allows other threads to automatically activate
• When I/O available, thread wakes back up again
– Becomes “runnable”
– Not to be confused with the Runnable interface

Thread Scheduling
• In general, the runnable thread with the highest priority is active (running)
• Java is priority-preemptive
– If a high-priority thread wakes up, and a low-priority thread is running
– Then the high-priority thread gets to run immediately
• Allows on-demand processing
– Efficient use of CPU

Thread Starvation
• If a high priority thread never blocks
• Then all other threads will starve
• Must be clever about thread priority

Thread Priorities: General Strategies


• Threads that have more to do should get lower priority
• Counterintuitive
• Cut to head of line for short tasks
• Give your I/O-bound threads high priority
– Wake up, immediately process data, go back to waiting for I/O

Race Conditions
• Two threads are simultaneously modifying a single object
• Both threads “race” to store their value

4 CCET
www.anuupdates.org
Network Programming – MC9241

• In the end, the last one there “wins the race”


• (Actually, both lose)

Race Condition Example


class Account {
int balance;
public void deposit(int val)
{
int newBal;
newBal = balance + val;
balance = newBal;
}
}

Thread Synchronization
• Language keyword: synchronized
• Takes out a monitor lock on an object
– Exclusive lock for that thread
• If lock is currently unavailable, thread will block

• Protects access to code, not to data


– Make data members private
– Synchronize accessor methods
• Puts a “force field” around the locked object so no other threads can enter
• Actually, it only blocks access to other synchronizing threads
• A rogue thread can "sneak in" and modify a variable it has access to

Synchronization Example
class Account {
private int balance;
synchronized public void deposit(int val)
{
int newBal;
newBal = balance + val;
balance = newBal;
}
synchronized public void withdraw(int val)
{
int newBal;
newBal = balance - val;

5 CCET
www.anuupdates.org
Network Programming – MC9241

balance = newBal;
}
}

Multithreaded Servers
– same thread accepts connect requests, then processes
– uses a forever loop
• Single thread here sufficient, quick response possible
• Longer task would cause backlog of client requests
• Each iteration of the processing loop will:
• accept connection request
• create a handler thread for that client
• server thread immediately returns to top of processing loop

for( ; ; ) {
Socket sessionSocket = myServerSocket.accept();
// create new thread for service using
// sessionSocket
// start the thread
}

Multithreaded Echo Server


• Server will read lines of text client sends
– echo back each line
– may be multiple lines, time consuming
• EchoServer class
– builds its ServerSocket
– repeatedly
invokes accept()
creates new EchoHandler thread for
each request

Thread Creation and Termination

Thread Creation Diagram

6 CCET
www.anuupdates.org
Network Programming – MC9241

Threads creation
Nearly all Linux distributions have thread frameworks
 e.g. POSIX (widely used standard in thread programming), called pthread.
Include of required header file:
 #include <pthread.h>
Compilation against Pthread library:
 gcc –lpthread <source>
Debugging tools like gdb or ddd support threads as well.
Before creating a thread:
• write or at least declare a tread function
• declare a thread handle (data type: pthread_t)
and prepare the attribute of this thread:
• data type for the attribute: pthread_attr_t
• detach state (PTHREAD_CREATE_JOINABLE, PTHREAD_CREATE_DETACHED)
• scheduling policy and schedule parameters
• stack size (size in bytes which is reserved for this thread in the stack)

Example:
void* thread_func(void* arg) {
// do something
}
int main() {
pthread_t t_handle;

7 CCET
www.anuupdates.org
Network Programming – MC9241

pthread_attr_t attr;
int status;
status = pthread_attr_init(&attr);
status = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
status = pthread_create(&t_handle, &attr, (void*) thread_func, NULL);
status = pthread_attr_destroy(&attr);
// do something else
}

Access to application data inside thread function:


 thread function has same access to application resources (data, functions) like calling
thread (main function)
 global variables or pointers (bad  concurrency problems, if not protected)
 dedicated access functions (good, if concurrency protection implemented)
 called functions are duplicates (both, main and thread func, can call the same function at
the same time, but they are not working on the same stack area)

Threads termination
A thread ends, when:
• “main” thread function finishes
• call of: void pthread_exit(void* exitVal); inside thread function
• call of: int pthread_cancel(t_handle); outside of thread function
• Note: call of exit() in thread exits whole process
Request of exit value of a thread:
int pthread_join(t_handle, &exitVal);
but terminated thread must have been created with PTHREAD_JOINABLE as attribute.
 Can be used for synchronisation: waits for termination of thread t_handle

8 CCET
www.anuupdates.org
Network Programming – MC9241

A thread can declare its cancel state:


• enable PTHREAD_CANCEL_ENABLE
• disable PTHREAD_CANCEL_DISABLE
 int pthread_setcancelstate(int state, int *oldstate)
And also the cancel type:
• immediate cancellation: PTHREAD_CANCEL_ASYNCHRONOUS
• cancellation at dedicated cancellation points: PTHREAD_CANCEL_DEFERRED
 int pthread_setcanceltype(int type, int *oldtype);
 Normally declared in beginning of thread, but can also be changed later on.

Threads frameworks
POSIX
 in most Linux distributions included
ACE
 The ADAPTIVE Communication Environment
http://www.cs.wustl.edu/~schmidt/ACE.html

TCP Echo server using Threads

Create thread

9 CCET Thread function

Figure 26.3 TCP echo server using threads (see also Exercise 26.5)
www.anuupdates.org
Network Programming – MC9241

Passing Arguments to New Threads

Figure 26.4 TCP echo server using threads with more portable
argument passing.
10 CCET
www.anuupdates.org
Network Programming – MC9241

Mutexes

Mutual Exclusion

Consider the following scenario:


 Thread A is running and it loads the value of nconn (3) into a register.
 The system switches threads from A to B. A’s registers are saved, and B’s register are
restored.
 Thread B executes the three instructions corresponding to the C expression nconn--,
storing the new value of 2.
 Sometime later the system switches thread from A to A. A’s register are restored and A
continues where it left off, at the second machine instruction in the three-instructions
sequence

Figure 26.17 Two threads that increment a global variable


incorrectly.
Solution
o To protect the shared variable with a mutex and access the variable only when we hold
the mutex.
o A mutex is a variable of type pthread_mutex_t.
o Two function of mutex – lock and unlock

11 CCET
www.anuupdates.org
Network Programming – MC9241

Control Variables

A mutex is fine to prevent simultaneous access to a shared variable, but we need something else
to let us go to sleep waiting for some condition to occur.
We cannot call the Pthread function until we know that a thread has terminated
o declare a global that counts the number of terminated threads and protect it with a
mutex.

The main loop never


goes to sleep, and it
checks ndone every
time.
This is called polling
and is considered a
waste of CPU time

12 CCET
www.anuupdates.org
Network Programming – MC9241

Mutex and condition variables


o Mutex : provides mutual exclusion
o Condition variable : provides a signaling mechanism

Other Functions
pthread_cond_broadcast will wake up all threads that are blocked on the condition
variable.
pthread_cond_timewait lets a thread place a limit on how long it will block.

13 CCET
www.anuupdates.org
Network Programming – MC9241

Raw Sockets

Bypass TCP/UDP layers


Read and write ICMP and IGMP packets
o ping, traceroute, multicast daemon
Read and write IP datagrams with an IP protocol field not processed by the kernel
o OSPF
o user process versus kernel
Send and receive your own IP packets with your own IP header using the IP_HDRINCL socket
option
o can build and send TCP and UDP packets
o testing, hacking
o only superuser can create raw socket though
You need to do all protocol processing at user-level

14 CCET
www.anuupdates.org
Network Programming – MC9241

Creating a Raw Socket


int sockfd;
sockfd = socket(AF_INET, SOCK_RAW, protocol);
const int on = 1;
setsockopt (sockfd, IPPROTO_IP, IP_HDRINCL,
&on, sizeof(on);

Raw Socket Input


. UDP / TCP Never pass to Raw Socket
2. Most ICMP Kernel => Raw Socket
3. All IGMP Kernel => Raw Socket
4. All Unknown IP Datagram
Kernel ~> Raw Socket
5. Fragment In Reassemble ~> Raw Socket

15 CCET
www.anuupdates.org
Network Programming – MC9241

Raw Socket Output

1. Sendto / sendmsg + destination IP


connect => write / writev / send
2. Starting Address for the kernel to write
Starting Addr. = First byte following the IP header
Set IP_HDRINCL =>
Starting Addr. = First byte of the IP header
3. Fragmentation by kernel

Sending raw socket packets by sendto or sendmsg


o 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
o If IP_HDRINCL option set, the starting address of data in sendto() specifies the first byte
of the IP header.
o IP Header fields modified on sending by IP_HDRINCL
o IP Checksum Always filled in.
o Source Address Filled in when zero.
o Packet Id Filled in when zero.
o Total Length Always filled in.
o Example: see Steven’s code under ping/send_v4.c, ping/send_v6.c

Scatter read and gather write


Vectored IO
struct iovec {
void *iov_base; /* addr. Of buffer */
size_t iov_len; /* size of buffer */
}

Send and receive from one or more buffers with a single function call.

16 CCET
www.anuupdates.org
Network Programming – MC9241

Ping Program

Create a raw socket to send/receive ICMP echo request and echo reply packets
Install SIGALRM handler to process output
o Sending echo request packets every t second
o Build ICMP packets (type, code, checksum, id, seq, sending timestamp as optional data)
Enter an infinite loop processing input
o Use recvmsg() to read from the network
o Parse the message and retrieve the ICMP packet
o Print ICMP packet information, e.g., peer IP address, round-trip time
Source code: Steven’s under ping/

Overview of Ping

17 CCET
www.anuupdates.org
Network Programming – MC9241

Trace Route Program

Create a UDP socket and bind source port


o To send probe packets with increasing TTL
o 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
o If timeout, printing “ *”
o If ICMP “port unreachable”, then terminate
o If ICMP “TTL expired”, then printing hostname of the router and round trip time to the
router
Source code: Steven’s traceroute/

18 CCET
www.anuupdates.org
Network Programming – MC9241

Example of Traceroute

Solaris # traceroute gemini.tuc.noao.edu


traceroute to gemini.tuc.noao.edu (140. 252. 3. 54): 30 hops max, 12 data bytes
1 gw.kohala.com (206.62.226.62) 3.839ms 3.595ms 3.722ms
2 tuc -1 -s1 -9 .rtd.net (206.85.40.73) 40.014ms 21.078ms 18.826ms
3 frame -gw.ttn.ep.net (198.32.152.9) 39.283ms 24.598ms 50.037ms
.
.
.
7 gemini.tuc.noao.edu (140.252.3.54) 70.476ms 43.555ms 88.716ms

19 CCET

You might also like