Network Programmimg Unit 4

Embed Size (px)

Citation preview

  • 8/10/2019 Network Programmimg Unit 4

    1/85

    Unit

    -

    IV

    ADVANCED OCKETS

    4.1

    IPV4 and IPv6

    Interoperability

    4.1.1Introduct ion

    A

    gradual

    ransition

    of the

    Internet rom IPv4

    (Current

    version) o

    IPv6

    (Next

    generation)

    is

    probably

    equired.So t is important hat

    existing Pv4

    applications

    ontinue o

    work with

    newer Pv6 applicat ions.

    .

    An IPv6 Telnet servers

    must

    provide

    one

    that

    works with IPv4 servers

    and one

    that work's

    with IPv6 servers.

    .

    One

    IPv6 Telnet client that can

    work

    with

    both

    IPv4 and

    IPv6 servers,.

    .

    One Telnet sever hat can

    work with both

    IPv4

    and

    IPv6 clients.

    .

    The hosts are

    running

    dualstacks,that

    s

    both

    and IPv4

    protocol

    stack and an

    IPv6

    protocol

    stack.

    There are four combi nationsof

    clients and serversusing

    either IPv4

    or IPv6 and we

    show hese n

    Figure4.1

    Fig 4.1

    combinations

    of clients and server s using

    IPv4 or IPv6.

    The following conceptsare discussedn this chapter.

    .

    IPv4

    client,

    IPv6 serverover dual-stack erver

    host

    .

    IPv6 client over dual-stack lient

    host, Pv4 server

    .

    IPv6 address

    macro, unction and option

    . Sourcecodeportability

    IPv4 server lPv6server

    Pv4

    client

    Pv6client

    Almostal l exist ing

    clientsandservers

    Discussedn

    section

    .1.3

    Discussedn sec t ion

    .1.2

    Simple

    modification to most

    exist ine

    cl ientsand servers

    AdvoncedSockets

    4.3

  • 8/10/2019 Network Programmimg Unit 4

    2/85

    4.1.2 lPv4 C lient,

    IPv6 server

    A

    general

    property

    of a dual-stack

    host s that IPv6 servers

    an

    handleboth

    IPv4

    and

    IPv6 clients.

    This is done using IPv4

    mapped Pv6 addresses.

    igure

    4.2

    shows

    an example

    of

    this.

    lPv6 istening

    socketbounded

    to 0::0,

    port

    8888

    lPv4-mapped

    lPv6address

    lPvO ddress

    zvo.oz.zzo.+z

    5f1 :df00:ce3e:e200:

    2O:80O:2b37:6426

    Type

    Dport

    0800 8888

    J;ffi?ffi'

    Fig 4.2 IPv6 server on dual

    -stack

    host serving IPv4 and

    IPv6

    clients

    From the fig 4.2 :

    .

    An IPv4 client and an IPv6 client are on the eft. The server

    on

    the

    risht is written

    using Pv6 and t is runningon a dual-stack ost .

    .

    The server has createdan IPv6 listenrngTCP socket hat

    is

    bound to the

    IPv6

    wildcardaddress

    nd

    TCP

    port

    8888.

    .

    Assume hat the clients and serverare on the sameEthernet.

    .

    Routerscould alsoconnect hem,as ong asall the routerssupport Pv4 and Pv6.

    .

    Assume hat both clients send

    SYN sesments o

    establish

    a

    connectionwith

    the

    server.

    IPV4

    cl ient

    .

    The IPv4 client host will

    send he SYN in an IPV4 datagrams

    .

    The TCP

    segment

    rom

    the IPv4 client appears

    n

    the

    wire

    as

    an Ethernetheader

    followed by and IPv4 header, TCP header,

    nd the TCP data.

    .

    The Ethernetheader ontainsa

    type field of oxo800,which identrfies he frame

    as

    an

    IPv4

    frame.

    .

    The TCP header ontains he dest inat ion

    ort

    of 8888.

    .

    The destination P address n the IPv4 headerwould

    be 206.62.226.42.

    lHVtl

    cl ient

    lPv4

    cl ient

    Enet

    nd r

    Pv 4

    hdr hdr

    TC P

    oata

    no r

    Enet

    lPv6

    no r

    TCP

    hd r

    TC P

    oala

    4.4

    Network rogramming

    nd Management

  • 8/10/2019 Network Programmimg Unit 4

    3/85

    IPVS client

    .

    The

    IPv6

    client's

    host

    will send

    he

    SYN

    in an

    IPv6

    datagram.

    .

    The

    TCP

    segment

    rom

    the

    IPv6 client

    appears

    on

    the

    wire as

    an

    Ethernet

    header

    followed

    by

    and

    IPv6

    anlPv6

    header,

    TCP

    header,

    and

    the

    TCP

    data.

    .

    The Ethernet

    header

    contains

    a type

    field

    of

    0x86dd,

    which

    identifies

    the

    frame as

    an IPV6

    frame.

    .

    The TCP

    header

    n the

    IPV6

    packet

    has

    he

    same

    ormat

    as the

    TCP

    header

    n the

    IPV4 packet,and contains he destinationport of 8888'

    .

    The

    des t ina t ion

    IP

    address

    in

    the

    IPv6

    header

    wou ld

    be

    5 I b :df00

    c

    e3e:200

    20

    800

    2b37

    6426.

    The

    receiving

    datalink

    looks

    at the

    Ethernet

    type

    field

    and

    passes

    each

    frame

    to the

    appropriate

    P module.

    Address

    conversion

    .

    The

    IPv4

    module,

    probably n conjunction

    with

    the

    TCP

    module,

    detects

    hat he

    destination

    socket

    s

    an IPv6

    socket,

    and the

    source

    PV4

    address

    n

    the IPV4

    header

    s converted

    nto the equivalent

    PV4-mapped

    PV6

    address.

    . That mappedaddress s returned o the IPv6 socketas the client's IPv6 address

    when accept

    eturns

    o

    the server

    with the

    IPv4 client

    connection'

    .

    All

    remaining

    datagrams

    or

    this connection

    are

    Pv4

    datagrams.

    .

    When accept

    eturns

    o

    the

    server

    with

    the

    IPv6 client

    connection,

    he

    client's

    IPv6

    address

    does

    not change

    rom

    whatever

    source

    address

    appears

    n

    the IPv6

    header.

    .

    All remaining

    datagrams

    or this connection

    are

    Pv6

    datagrams.

    We can summarize

    he

    steps hat

    allow

    an

    IPv4

    TCP client

    to communicate

    with an

    IPv6 server.

    l. The lpv6 serverstarts,createsan IPv6 listeningsocket,and t binds the wildcard address

    to the

    socket.

    2.

    The IPv4

    client calls

    gethostbyname

    and finds

    an

    A record

    for

    the server.

    The

    server

    host

    will

    have both

    an

    A record and

    a AAAA

    record, since

    t supports

    both

    protocols

    but the

    IPv4

    client asks

    for

    only an

    A record.

    3.

    The client

    calls connect

    and

    he client's

    hostssend

    an

    IPV4 SYN

    to

    the server.

    4. The server

    host eceives

    he

    IPv4 SYN

    directed

    o

    the

    IPV6

    listening

    socket,

    etaa

    flag

    indicating

    hat

    this connection

    s using

    IPV4

    -mapped

    IPV6

    addresses

    nd

    responds

    with an

    IPV4 SYN/ACK.

    When the connection

    s established,

    he

    address

    eturned

    to

    the server

    by accept

    s the

    IPv4 mapped

    Pv6 address.

    5.

    All

    communication

    between his client and server akesplace using IPv4 datagrams.

    AdvoncedSockefs

    4.5

  • 8/10/2019 Network Programmimg Unit 4

    4/85

    6.

    Unless the

    server explicitly

    checks

    whether

    his IPv6 address s and IPv4 mapped

    Pv6

    address

    using

    the

    IN6_Is_l DDR_V4MAPPED macro),

    the server never knows that it

    is

    communicatingwith

    an IPv4 client. The

    dual

    protocol

    stack handles his detail.

    Similarly,

    the

    IPv4

    client has no idea

    that

    it

    is communicating with an IPv6

    server.

    An

    underlying

    assumption n this scenario s

    that the dual

    -

    stack server host has

    both

    an IPv4 address

    and an IPv6

    address.This will work

    until all

    the IPv4

    addresses re taken.

    The

    scenario s similar for an IPv6

    UDP server,but the

    address

    ormat

    can change or

    each datagram.For example, f the IPv6 server receives a datagram rom an IPv4 client, the

    address eturned

    by recvfrom will

    be the client's IPv4

    mapped IPv6 address. The

    server

    responds

    o this

    client's requestby calling

    sendto

    with

    the IPv4 mapped Pv6

    address s he

    destination.

    his

    address ormat tells the kernel

    o sendan IPV4

    datagram

    o

    the client. But

    the next datagram

    eceived for the

    server would

    be

    IPV6

    datagram.But the next datagrams

    received or

    the servercould

    be an IP

    v6

    datagrams,

    nd recvfrom will return the IPv6

    address.

    It the

    server esponds,

    he kernel will

    generate

    an IPv6

    datagrar4.

    Figure

    4.3 summarizes

    ow a received

    Pv4 or IPv6 datagram s

    processed,

    epending

    on the

    type

    of

    the receiving

    socket, for

    TCP and

    UDR assuming a dual stack host.

    lPv4sockets

    AF-INET

    SOCK-DGRAM

    sockaddr_in

    AF_INET6

    SOCK-STREAM

    sockaddr_in6

    AF ' INET6

    SOCK-DGRAM

    sockaddrn6

    { , , *

    4.6

    revo

    ocr

  • 8/10/2019 Network Programmimg Unit 4

    5/85

    o Ifan

    IPv6 datagram

    s

    received

    for an

    IPv6 socket,

    nothing

    special

    is done

    These are the

    two arrows

    labeled

    IPv6

    in the

    figure, one

    to TCP

    and one

    to

    UDP.

    IPv6 datagrams

    are exchanged

    between

    he client

    and server.

    o But

    when an

    IPv4 datagram

    s

    received

    for an

    IPv6 socket,

    the

    kernel

    returns

    the corresponding

    IPv4 mapped

    Pv6 address

    as

    the address

    eturned

    by

    accept(TCP)

    or recvfrom

    (UDP).

    These

    are the two

    dashed

    arrows

    in the

    figure.

    This mapping

    s

    possible

    because

    n

    IPv4 address

    an

    always

    be

    representedas an IPv6 address. PvA datagrams re exchangedbetween he

    client and server.

    The converse

    ofthe

    previous

    bullet

    (an

    Ipv6

    datagram

    s received

    or

    an Ipv4

    socket)

    is

    false:

    in

    general

    an

    IPv6 address

    connote

    be represented

    as an

    IPv4 address:

    herefore

    there are no arrows

    from the

    IPv6

    protocol

    box to

    the two

    IPv4 sockets.

    Most dual- stack

    hostsshould

    use he

    following

    rules

    n

    dealing

    with listening

    sockets:

    l. A listening Pv4

    socketcan

    accept

    ncoming connections

    rom only

    IPv4 clients.

    2. Ifa

    server

    has a

    listening Pv6

    socket hat

    hasbound

    he

    wildcard address,

    hat socket

    can accept incoming connections from either IPv4 clients or IPv6 clients. For a

    connection

    rom an Pv4 client

    the server's

    ocal address

    or the

    connection

    will

    be he

    corresponding

    Pv4 mapped

    Pv6 address.

    3.

    If

    a server

    has a l istening

    IPv6 socket

    hat has bound

    an IPv6 address

    other than an

    IPv4 mapped Pv6 address,

    hat socket

    can accept

    ncoming connections

    rom

    IPv6

    clients only.

    4.1.3 IPv6 cl ient , IPv4

    serve

    Consideran

    IPv6 TCP client running

    on a dual

    -stack

    host

    l. An IPv4 serverstartson an

    lPv4-only host and

    createsan IPv4

    listening socket.

    2. The IPv6 client starts,calls

    gethostbyname

    sking or only

    IPv6 addresses

    It

    enables

    the

    RES_USE_INET6

    option). Since he

    IPv4-only server

    host has only A records, an

    IPV4-mapped IPv6 address

    s returned to the client.

    3. The

    IPv6

    client calls

    connectwith the lPv4-mapped

    Pv6 address n the

    IPv6

    socket

    addressstructure.

    The kernel

    detects

    he mapped addressand

    automatically sendsan

    IPv4 SYN to the server.

    4.

    The server esponds

    with

    an IPv4 SYN/ACK, and he

    connection s established

    sing

    IPv4 datagrams.

    We can summarize his scenario n Fieure4. 4

    Advonced

    Sockels

    4.7

  • 8/10/2019 Network Programmimg Unit 4

    6/85

    lPv4sockets

    AF-INET

    SOCK-DGRAM

    sockaddr_in

    {

    { , * .

    AF_INET6

    SOCK-STREAM

    sockaddr_in6

    AF-INET6

    SOCK-DGRAM

    sockaddr_in6

    Pv6sockets

    address

    returned y

    accept r

    recvfrom

    lPv4datagram lPv6datagram

    Fig, 4.4 processing of client rcquests, depending on address type and socket type

    .

    If

    an

    IPv4 TCP client

    calls

    connect

    specifyingan IPv4 address,

    r if

    an

    IPv4 UDP

    client calls send o specifyingan Pv4 address, othing special s done.Theseare

    the two arrows labeled

    IPv4

    in the figure.

    .

    If an IPv6 TCP client calls connect

    specifyingan

    IPv6

    address, r if an IPv6 UDP

    client calls sendtospecifyingan IPv6

    address,

    othing

    special s doneTheses re

    the two

    arrow

    labeled

    IPv6 in

    the figure

    .

    If

    an

    IPv6 TCP

    client specifiesan IPv4-mapped Pv6

    address

    o

    connector if an

    IPv6 UDP client

    specifies an IPv4-mapped IPv6 address

    o sendto, the

    kernel

    detects he mappedaddress

    nd causes

    n

    IPv4 datagram o

    be sent,

    nstead

    ofan

    IPv6 datagram.Theseare the two dashedarrows in the figure.

    .

    An IPv 4 client

    cannot

    specify

    an Pv6 address o either

    connector sendtobecause

    a l6 -byte IPv6 address

    oesnot fit in the 4-byte n_addr

    structurewithin the IPv4

    sockaddr_in structure. Therefore

    there are no arrows from the IPv4

    clients to the

    IPv6

    protocol

    box

    in

    the

    figure.

    In

    an IPv4 datagram arriving for

    an IPv6 server socket, he

    conversion ofthe received

    address o the IPv4-mapped Pv6

    address s done

    by

    the kernel

    and returned transparently o

    the

    applicationby accept

    or

    recvfrom.

    In

    an IPv4 datagramneeding

    o be senton an IPv6

    socket he conversionofthe IPv4

    address o

    the

    IPv4-

    mapped Pv6 address

    s done by the resolverand

    the

    mapped

    addresss

    thenpassed ransparently y the application o connector sendto.

    Network rogramming

    nd

    Management

    .8

  • 8/10/2019 Network Programmimg Unit 4

    7/85

    Summary

    of

    interoPerabilitY

    Figure

    4.5 summarizes

    his

    section

    and

    the

    previous section

    and

    the

    combinations

    of

    clients

    and

    servers.

    IPv4

    server

    IPv4-only

    host

    (A

    only)

    IPv6server

    IPv6-only

    host

    (AAAA

    only)

    IPv4

    server

    dual-

    stack

    host

    (A

    and

    AAAA)

    IP6server

    dual

    stack

    host

    (A

    and

    AAAA)

    lPv4

    client,

    IPv4-

    onlY

    host

    IPv4

    (no)

    IPv4

    IPv4

    IPv6

    cl

    ent,

    Pv6

    only

    host

    (no)

    IPv6

    (no)

    IPv6

    IPv4

    ci ent.

    dual-stack

    ost

    IPv4

    (no)

    IPv4

    IPv4

    IPv6

    client.

    dual-

    stack

    host

    IPv4

    IPv6

    (no*)

    IPv6

    Figure

    4.5 Summary

    of

    interoperability

    between

    Pv4

    and

    IPv6

    clients

    and

    servers

    Each

    box

    contains IPv4

    or

    IPv6

    if the

    combination

    s OK,

    indicating

    which

    protocol

    is used,

    (no) -if

    the combination

    s invalid.

    The

    third

    column

    on

    the

    final row

    is

    marked

    with

    an asterisk

    because

    nteroperability

    depends n the address hosenby the client.

    Choosing

    he

    AAAA

    record

    and

    sending

    an

    IPV6

    datagram

    will

    not

    work.

    But

    choosing

    the

    A record,

    which

    is returned

    o the

    client

    as

    an

    IPv4-

    mapped

    Pv6

    addresses'

    auses

    n

    IPv4

    datagram

    o be

    sent,

    which

    will

    work'

    Although

    it appears

    hat

    one-fourth

    of

    the table

    will

    not

    interoperate,

    n the

    real

    world

    for

    the

    foreseeable

    uture,

    most

    implementations

    f

    IPv6

    will

    be on

    dual

    -

    stack

    hosts

    and

    will

    not

    be IPv6-

    only

    implementations.

    f

    we then

    emove

    he

    second

    ow

    and

    second

    olumn,

    al l

    of the

    (no)

    entries

    disappear

    and the

    only

    problem

    is the

    entry

    with

    the

    asterisk.

    4.1.4 IPv6 Address Testing Macros

    IPv6

    Address

    Macro,

    Function,

    Option

    .

    IPv6 address

    esting

    macros:

    N6-IS-ADDR-*

    (e.g. V4MAPPED)

    .

    Protocol

    ndependent

    ocket

    address

    unctions:

    sock-*

    (e.g.

    cmp-addr)

    .

    IPv6_ADDRFORM

    socket

    option:

    change

    a socket

    type

    between

    IPv4

    and

    IPv6,

    by

    setsockopt

    unction

    with

    IPv6-ADDRFORM

    option

    There

    are

    small

    classes

    of

    IPv6 applications

    that

    must

    know

    whether

    they

    are talking

    to an

    IPv4

    peer.These

    applications

    need to

    know

    if the

    peer's address

    s an

    IPv4

    mapped

    IPv6 address.Twelve macros are defined to test an IPv6 address or certain properties.

    4.9

    Advonced

    Sockets

  • 8/10/2019 Network Programmimg Unit 4

    8/85

    f,include

    f_name);

    4.40

    Network rogrammingndManagement

  • 8/10/2019 Network Programmimg Unit 4

    39/85

    )

    pri

    ntf

    "end-of-f

    e on

    o/os\n

    ,

    f

    ptr->

    -n ame)

    Close(fd);

    fptr->f-flags

    F-DoNE;

    /*

    clears

    F-READING

    /

    return(fpt0;

    /*

    terminate

    hread

    /

    l

    /*

    end do_get_read

    /

    Fig.

    4. 2

    5

    do-g et-rea

    d

    fu

    n ctio

    n

    From he

    ig.4.25,

    These wo

    decrements

    re

    placed n the do_get-read

    unction

    n

    which

    each

    hread

    decrement

    hese

    wo

    counters

    mmediately

    efore

    he hread

    erminates.

    t results

    n a

    slight

    concurrent

    rogrammlng rror.

    The

    problem n the

    unction

    hat

    each hread

    xecutes

    s

    that

    hese wo

    variables

    re

    global,

    not thread-specific.

    f one hread

    s in

    the middle

    of decrementing

    variable, hat

    thread

    s suspended,

    nd

    another

    hread

    executes

    nd

    decrements

    he

    same

    ariable, n

    error

    can esult.

    For

    example,

    Assume hat

    the

    C compiler

    urns

    the

    decrement

    perator

    nto 3

    instructions:

    .

    Load

    rom

    Memory

    nto a

    register.

    .

    Decrement

    he

    register.

    .

    Store

    rom

    the

    register

    nto

    memory.

    Possible

    cenarios

    Thread

    A is

    running

    and

    t loads

    hevalue

    of nconn

    nto a

    register.

    l. The system

    witches

    hreads

    rom

    A to B.A's

    egisters

    re

    saved nd

    B's

    registers

    re

    restored.

    2. ThreadB executeshe hree nstructionsorrespondingo theC expressionsconn-

    ,

    storing

    he

    valueof

    2.

    3.

    Sometime

    ater

    he system

    witches

    hreads

    rom B

    to A.

    A's

    registers

    re estored

    nd

    A

    continues

    here t left

    off, at he

    second

    machine

    nstruction

    n the

    hree-

    nstructions

    sequence:

    he

    valueof

    the register

    s decrements

    rom

    3 to

    2

    and he

    value

    of 2 is

    stored n

    nconn

    The end

    esult

    s that

    nconn

    s 2

    when t should

    e

    l. This

    s

    wrong.

    These

    ypes

    of

    concurrent

    rogramming

    rors arehard

    o find

    for numerous

    easons.

    hey

    are

    o they

    occur

    arely.

    Nevertheless

    t is an

    error

    and

    t

    will fail

    (Murphy's aw)

    .

    o the error s hard o duplicate, ince, t depends n thenon-deterministiciming

    of many

    events.

    AdvoncedSockels

    4'41

  • 8/10/2019 Network Programmimg Unit 4

    40/85

    o

    On

    some systems

    he

    hardware

    nstructions

    might

    be atomic;

    that is there

    exists

    a hardware

    instruction

    to decrement

    an integer

    in memory

    and the

    hardware

    cannot

    be interrupted

    during

    this

    instruction.

    But this

    is not

    guaranteed

    y all systems,

    so the code works

    on one

    system

    but not

    on another.

    Threads

    programming

    s

    also called

    as concurrentprogramming

    or

    parallel

    programming

    since

    multiple

    hreads an

    be

    running

    concurrently

    in

    parallel)

    accessing

    he same ariables.

    Fig.4.26

    is a

    simple

    program

    hat

    creates

    wo threads

    and then has

    each hread

    ncrement

    a global variable5000 times.

    #include

    "unpthread.h"

    #define

    NLOOP

    000

    int

    counter;

    /*

    this s ncremented

    y the

    hreads

    /

    void

    *doit(void

    );

    int

    main(int

    rgc,

    char

    *argv)

    {

    pthread_t

    tidA, idB;

    Pthread_create(&tidA,

    ULL,

    &doit,NULL);

    Pthread_create(&tidB,

    ULL,

    &doit,NULL);

    /* 4wait or both hreadso terminate

    /

    Pthreadjoin(tidA,

    ULL)

    Pthreadjoin(tidB,

    ULL)

    exit(0);

    )

    void

    doit(void

    vptr)

    {

    int

    i , val;

    t ,

    *

    Each

    hread etches,

    r ints,

    nd ncrements

    he

    counterNLOOPimes.

    *

    The

    valueof the counter

    hould ncrease

    monotonically.

    *l

    for

    ( i

    =

    0;

    int

    pthread_mutex_lock

    pthread-mutex-t

    mptr)

    Int pthread_mutex_trylockpthread-mulex-t

    mplr)

    int

    pthread_mutex_unlock

    pthread_mutex-t

    mptr)

    Both

    eturn:

    if OK

    positive

    xxx

    alue

    on error

    If

    we

    try to

    lock

    a mutex

    hat s already

    ockedby

    some

    other

    hread,

    we

    are

    blocked

    until the

    mutex

    s unlocked.

    o The

    pthread_mutex_lock0

    outine

    s used

    by a

    thread

    o acquire

    lock

    on the

    specified

    mutex

    ariable.

    f the

    mutex

    s already

    ocked

    by another

    hread,

    his

    call

    will

    block

    he

    calling hread

    ntil he

    mutex

    s unlocked.

    o

    pthread_mutex_trylock0

    ill attempt

    o

    lock a

    mutex.

    However,

    f the

    mutex s

    already

    ocked,

    he routine

    will return

    mmediately

    ith

    a

    "busy"

    error

    code.

    This

    routine

    maybe useful

    n

    preventing eadlock

    onditions,

    s n a priority-

    inversion

    ituation.

    o

    pthread_mutex_unlock0

    ill unlock

    a

    mutex f

    called

    by the

    owning

    thread.

    Calling

    his

    routine

    s

    required

    fter

    a thread

    ascompleted

    ts use

    of

    protected

    data

    f other

    hreadsare

    o acquire

    he

    mutex

    or their

    work

    with the

    protected

    data.

    An error

    will be returned

    f:

    o

    If the mutex

    wasalready

    unlocked

    o

    If the

    mutex

    s owned

    bv another

    hread

    Usage

    o

    Mutex

    variables

    must be

    declared

    with type

    pthread-mutex-t,

    nd

    must

    be

    initialized

    before

    hey can

    be used.

    There

    are two

    ways to

    initialize

    a mutex

    variable:

    l. Statically,

    hen t is

    declared.

    or

    example:

    pthread-mutex-tmymutex

    =

    PTHREAD-

    MUTEX-INITIALIZER;

    2.

    Dynamically,

    with the

    pthread_mutex_init0

    outine.

    This

    method

    permits

    setting

    mutexobject

    attributes,

    /lr.

    Fig.4.27

    s a corrected

    ersion f

    Fig.4.26

    hat

    uses

    single

    mutex

    o ock

    hecounter

    betweenhe wo threads.

    Advonced Sockefs

    4.43

  • 8/10/2019 Network Programmimg Unit 4

    42/85

    #include

    "unpthread.h"

    #define

    NLOOP 000

    int

    counter;

    /*

    this

    s ncremented

    y the hreads

    /

    pthread_mutex_t

    counter_mutex PTHREAD_MUTEX_lNlTlALlZER;

    void

    *doit(void );

    in t

    main(int

    rgc,char

    *argv)

    t

    pthread_t

    tidA, idB;

    Pthread_create(&tidA,ULL,&doit,NULL);

    Pthread_create(&tidB,ULL,

    &doit,

    NULL);

    l*

    4wail or

    both threads o terminate

    /

    Pthreadjoin(tidA, ULL)

    Pthreadjoin(tidB, ULL)

    exit(0);

    )

    void

    *

    doit(void

    vptr)

    {

    int i , val;

    l*

    * Each hread etches, rints, nd ncrementshe counterNLOOPimes.

    *rThe

    value

    of

    the counter hould ncreasemonotonically.

    for

    ( i

    =

    0;

    sasend->sa_family,OCK_RAW,

    r->icmpproto);

    setuid(getuid0);

    /*

    don't

    need

    pecial

    ermissions

    nymore

    /

    size

    =

    60

    *

    1024;

    /*

    OK f setsockoptails

    /

    setsockopt(sockfd,

    OL_SOCKET,O_RCVBUE

    size, izeof(size));

    sig_alrm(SIGALRM);

    *

    send

    irst

    packet

    /

    f o r ( ; ; ) {

    1sn

    pr->salen;

    n

    =

    recvfrom(sockfd,ecvbuf,

    izeof(recvbuf),

    ,

    pr->sarecv,

    len);

    i l ( n < 0 ) {

    i f

    (errno

    =

    EINTR)

    continue;

    else

    err_sys("recvfromrror")

    )

    Gettimeofday(&tval,ULL)

    (*pr->fproc)(recvbuf,

    , &tval);

    )

    )

    Fig. 4.

    3

    4 read

    oop

    unct

    ion

    Create

    socket

    o

    { raw socketofthe appropriate

    rotocol

    s created.

    . The call to setuid setsour eff ective user D to our real user D.

    .

    The

    program

    must have

    super

    user

    privileges

    o

    create he raw socket,but now

    that

    the

    socket

    s

    created,and the extra

    privileges

    are

    given

    up .

    .

    It is

    always

    best

    o

    give

    up this extra

    privilege

    when it is no longer needed.

    Set socket receive buffer

    .

    The socket

    eceive buffer

    size

    s

    set to 61,440 bytes(60X1024)

    which should be

    larger than the default.

    .

    The

    user

    pings

    either the

    IPv4

    broadcast

    address

    or a relticast addresseither of

    which

    can

    generate

    lots of replies.

    .

    By making the buffer large4 thereis a smaller chance hat the socketreceive buffer

    will overflow.

    Advonced

    Sockets

    4.65

  • 8/10/2019 Network Programmimg Unit 4

    64/85

    Send

    irst

    packet

    .

    Signal

    handler

    s called

    which sends

    packetand

    schedules

    SIGALRM

    for one

    second

    n future.

    .

    It is

    not common

    o see

    a signal

    handler

    called

    directly

    but

    it is

    ok .

    o

    d

    s igna l

    hand le r

    is

    jus t

    a

    C func t ion ,

    eventhough

    t

    is norma l ly

    ca l led

    asynchronously

    y the

    kernel.

    Infinite

    loop

    reading

    all ICMP

    messages

    .

    The

    main oop

    of

    the

    program s

    an nfinite

    loop

    that

    reads

    all

    packets

    eturned

    on

    the

    RAW

    ICMP

    sockets.

    .

    Gettimeofday

    s called

    to

    record

    the time

    that

    the

    packet was

    received

    and

    then

    call

    the

    appropriate

    protocol function(proc-v4

    or

    proc-v6) to

    process

    ICMP

    messages.

    Fig .4.35

    shows

    the

    proc_v4

    function

    which

    processes

    all

    received

    CMPv4

    messages.

    .

    It

    is also realizedthat

    when the

    ICMPv4

    message

    s received

    by

    the

    process n the

    RAW

    socket,

    he kernel

    has already

    verified

    that

    the basic

    fields

    in the

    IPv4

    header

    and

    n the

    ICMPv4

    header

    are

    valid.

    # inc lude

    "p ing .h"

    void

    proc_v4(char

    ptr,

    ssize-t

    en,struct

    imeval

    tvrecv)

    {

    in t h len l ,

    cmp len ;

    double

    rtt ;

    struct

    p

    * ip;

    struct

    cmp

    *icmp;

    struct imeval

    tvsend:

    ip = (structp *) ptr; /* startof lP header'/

    hlenl

    =

    ip->ip_hl

    icmp_type

    =

    ICMP_ECHOREPLY)

    if

    ( icmp->icmp_id

    =

    Pid)

    return;

    /"

    not a respon se

    o our

    ECHO-REQUEST

    /

    if

    ( icmplen

    16)

    err_quit(" icmplen

    %d)

    sasend ai->ai_addr; /* contains estinationddress /

    4.76

    Network

    Programming

    nd

    Management

  • 8/10/2019 Network Programmimg Unit 4

    75/85

    pr->sarecv

    Cal loc(1,

    i ->ai_addr len);

    pr->salast

    =

    Cal loc(1

    ai ->ai_addr len);

    pr->sabind

    =

    Cal loc(1, i ->ai_addr len);

    pr->salen

    =

    ai ->ai_addr len;

    t raceloop0;

    exi t (0) ;

    Fig.4,45 Main

    function

    for

    traceroute

    prograrfl'

    Define

    proto

    structures

    The two

    proto

    structures

    redefined,

    one

    or IPv4

    and

    one

    or IPv6,

    although

    he

    pointer

    o

    thesocket

    ddress tructures

    renot allocated

    ntil

    the end

    of

    this

    unction.

    Set

    Defaults

    .

    The

    maximum

    TTL

    or Hop limit

    that the

    program

    uses

    defaults

    230.

    .

    The

    -m

    commandline

    option

    is

    provided o let

    the user

    change

    his'

    .

    For each

    TTL three

    probe packetsare sent

    but

    this could

    be

    changed

    with

    anothercommand ine option.

    .

    The intial

    destination

    port

    is 32768

    +

    666 and

    his

    will be

    incremented

    y

    one

    each ime

    a

    UDP

    datagram

    s sent.

    .

    These

    ports

    are not in use on

    the destination

    ost

    when the

    datagrams

    inally

    reach he

    destination. ut there

    s

    no

    guarantee.

    Process

    Command

    Line

    Argument

    The

    -v

    command

    ine option causes

    most

    received

    CMP

    messages

    o be

    printed.

    Process ostname

    or IP addressargument

    and f inish

    init ia l ization

    .

    The destination

    host nameor

    IP address

    s

    processed y our

    host-serv

    unction

    returning

    a

    pointer

    to an addrinfo

    structure

    .

    Depending

    on the

    type of returned

    address

    Pv4

    or IPv6,

    initializing

    the

    proto

    structure,store

    he

    pointer

    n the

    pr

    global

    and

    allocate

    additional

    socket

    address

    structureofthe correct

    size

    are finished.

    .

    The function

    traceloop

    shown

    in fig.4.46

    sends

    he datagrams

    and

    reads

    he

    returned CMP messages. his is the main loop of the program.

    4.77

    dvonced

    Sockefs

  • 8/10/2019 Network Programmimg Unit 4

    76/85

    #include

    " t race.h"

    void

    traceloop(void)

    t

    in t

    seq, code,

    done;

    double

    r t t ;

    struct rec

    *rec:

    struct imeval tvrecv;

    recvfd

    =

    Socket(pr- sasend-

    >

    sa_f mily,

    SOCK_RAW,

    r-

    >

    cmpproto)

    setuid(getuid0);

    / *

    don' t

    need

    specia l

    permissions

    ny

    more

    */

    sendfd

    =

    Socket (pr->sasend->sa_fami ly,

    OCK_DGRAM,

    );

    pr-

    >

    sabind-

    >

    sa_family

    =

    pr-

    sosnd- sa_f

    mi y;

    sport

    =

    (getpid0

    & oxff f f )

    0x8000;

    /*

    our source UDP

    porl#

    *l

    sock_set_port (pr->sabind,

    r->salen,

    tons(sport ) ) ;

    Bind(sendld,

    r->sabind,pr->salen);

    s ig_al rm(SIGALRM);

    seq

    =

    0'

    done

    =

    0;

    f o r

    ( t t l

    =

    1 ; t t l

    tt l level,pr->tt loptname,

    &ttl, sizeof(int))

    bzero(pr- salast,

    pr-

    >

    salen)

    pr int f ( "%2d

    ,

    t t l ) ;

    f f ush(stdout ) ;

    for

    (probe

    =

    0;

    probe rec_seq ++seq;

    rec->rec_ttl

    =

    t t l ;

    Gettimeofday(&rec- rec_tv,NULL)

    sock_set_port(pr->sasend,

    r->salen,

    htons(dport+ seq));

    Sendto(sendfd,

    endbuf ,datalen, ,

    pr->sasend, r ->salen);

    if

    ( (code

    =

    (*pr->recv)(seq,

    &tvrecv))

    ==

    -3 ;

    pr int f ( "

    " ) '

    / *

    t imeout ,

    no reply

    * /

    e lse

    {

    char st r INI_MAXHOST] ;

    if

    (sock_cmp_addr(pr->sarecv,

    r->salast,pr->salen)

    : 0)

    {

    if (getnameinfo(pr->sarecv, r->salen,str,sizeof(str),

    N U L L , 0 , 0 )

    =

    g ;

    printf("

    %s

    (o/os)",

    t r,

    Sock_ntop_host(pr-

    sarecv,

    pr-

    >

    salen))

    e lse

    printf("

    7os",

    Sock_ntop_host(pr->sarecv,

    r->salen));

    memcpy(pr->salast ,

    r ->sarecv, r ->salen);

    )

    tv_sub(&tvrecv,

    &rec-> rec_tv)

    rt t

    =

    tvrecv.tv_s ec 1000.0 +

    tvrecv.tv_us ec 1000.0;

    printf("

    %.31ms", rt t );

    if

    (code

    ==

    -1)

    /*

    port

    unreachable;

    t destination

    /

    done++:

    4.78

    Network rogrammingnd Management

  • 8/10/2019 Network Programmimg Unit 4

    77/85

    pr->sarecv

    Cal loc( ' | ,

    i ->ai_addr len);

    pr->salast

    Cal loc(1,

    i ->ai_addr len);

    pr->sabind

    =

    Cal loc(1,

    i ->ai_addr len);

    pr->salen

    =

    ai ->ai_addr len;

    t raceloop0;

    exi t (0) ;

    Fig.4.45

    Main

    function

    or

    traceroute

    rograu.

    Define

    proto

    structures

    The two

    proto

    structures

    are

    defined,

    one

    for IPv4

    and

    one

    for

    IPv6, although

    the

    pointer

    o the socket

    address

    tructures

    re not allocated

    until

    the

    end of

    this

    function.

    Set Defaults

    '

    The

    maximum

    TTL or

    Hop limit

    that the

    program usesdefaults

    230.

    .

    The

    -m

    commandline

    option

    is

    provided o let

    the user

    change

    his.

    .

    For each

    TTL three

    probe packetsare sent

    but

    this could

    be changed

    with

    anothercommand ine option.

    .

    The intial

    destination

    port

    is 32768

    +

    666 and

    this

    will be

    incremented

    y one

    each

    ime a UDP

    datagram

    s sent.

    .

    These

    ports

    are

    not in use on

    the destination

    host

    when

    the

    datagrams

    inally

    reach

    he

    destination, ut there

    s

    no

    guarantee.

    ProcessCommand

    Line Argument

    The

    -v

    command

    ine option causes

    most

    received

    CMP

    messages

    o

    be

    printed.

    Process

    ostname

    or

    IP addressargument

    and

    finish

    init ia l ization

    .

    The destination

    host

    name or

    IP address

    s

    processed y

    our host-serv

    unction

    returning

    a

    pointer

    to an addrinfo

    structure

    .

    Depending

    on the type

    of returned

    address

    Pv4

    or

    IPv6,

    initializing

    the

    proto

    structure,

    tore

    he

    pointer

    n the

    pr

    global

    and

    allocate

    additional

    socket

    address

    structure

    ofthe correct

    size

    are

    finished.

    .

    The function

    traceloop

    shown

    in fig.4.46

    sends

    he datagrams

    and reads

    he

    returned CMP messages. his is the main loop of the program.

    4.77

    Advonced

    Sockets

  • 8/10/2019 Network Programmimg Unit 4

    78/85

    else

    f

    (code

    >

    =

    0)

    pr intf(" ICMP

    %s)",

    *pr->icmpcode)(code)) ;

    )

    fflush(stdout);

    )

    pr intf" \n") ;

    i

    Fig.4.46 Traceloop

    unction

    : main

    processing loop.

    Create wo

    sockets

    .

    Two sockets

    re

    needed:

    raw socket n

    which

    all returned

    CMP

    are ead

    and

    a

    Udp socket

    on

    which a

    probe

    packets

    resent

    with the

    ncreasing

    TLs.

    .

    After

    creating

    raw socket,

    ureffective

    ser

    D to

    our

    ealuser

    D is

    reset,

    ince

    superuser

    rivileges renot onger

    equired.

    Bind source

    ort

    of UDP

    sockets

    .

    Bind a source

    ort

    o theUDP

    sockethat

    s used

    or sending,

    sing

    he ow

    order

    l5 bits

    of our

    process

    D

    with thehigh order

    bit

    set o

    I .

    .

    Since t

    is

    possible

    or multiple opies

    f the

    race

    outeprogramo be unning t

    any

    given

    ime

    it

    sneededo determine

    f a

    received

    CMP

    message

    as

    generated

    in response

    o oneof our datagrams,

    r in response

    o a dtagram

    ent

    by another

    copy

    of the

    program.

    .

    Thesource

    ort

    nt theUDPheader

    s used o

    dentify

    he

    sending

    rocess ecause

    the CMP

    message lways

    eturns

    he UDP header

    rom

    the

    datagram

    hat

    caused

    the CMP

    error.

    Establish

    ignal

    handler

    or SIGALRM

    Sig_alrm

    unction

    s established

    s he signal

    handler

    or

    SIGALRM

    because

    ach

    timea UDPdatagrams sentand3 secondss requiredo wait for an CMPmessageefore

    sendinghe

    next

    probe.

    Main oop;set TL

    or hop imit and

    send

    probes

    .

    The

    main

    oop of the unction

    s a

    double ested

    or

    loop'

    .

    The

    outer oop

    stars he

    TTL

    at I and

    ncreases

    y it to

    l,while

    the

    nner oop

    sends

    probes

    o the destination.

    .

    Each ime, he

    TTL changes

    etsockopt

    s called

    o set he

    new

    valueusing

    either

    IP_TTL

    or

    IPV6_UNICAST-HOPS

    ocket

    option.

    . Each imearound heouter oop, he socketaddress tructures initialized o 0.

    Advonced

    Sockcls

    4.79

  • 8/10/2019 Network Programmimg Unit 4

    79/85

    .

    This structure

    will be compared o the

    socketaddress

    tructure

    eturnedby

    recvfrom

    when he ICMP

    message

    s

    read,and

    f

    the

    2 structures

    re different,

    he IP address

    from the

    new structure s

    printed.

    .

    Using this technique he IP address

    orresponding

    o

    the first

    probe

    for each

    TT L

    is

    pr inted

    .

    If the

    IP

    addresschanges

    or a

    given

    value of

    TTL, the new

    IP

    address

    s then

    printed.

    Read CMP message

    The

    functions

    recv_v4 0r recv_v6 calls recvfrom

    to read

    and

    process

    he ICMP

    messages

    that are eturned.

    These

    2 functions return

    -3

    if

    a timeout

    occurs,

    2

    if an ICMP

    "time

    exceeded

    in transit"

    error is received, I

    if

    an

    ICMP

    "port

    unreachable"

    rror

    is received,or the

    no n

    negative CMP

    code

    f

    some

    other

    ICMP

    destination

    error

    is received.

    Print

    reply

    .

    If

    this

    is

    a

    first reply for

    a

    given

    TTL or if

    the IP addresss

    f the node sending

    he

    ICMP message aschanged or the

    TTL,the hostname

    and P addresss re

    printed.

    .

    The RTT is calculatedas the time difference rom when the probe is sent o the

    time the ICMP m essages returnedand

    printed.

    Our

    recv_v4 function is shown nthe

    fig.4.47

    #include

    "trace.h"

    *

    Return:

    3

    on imeout

    *

    -2

    on ICMP

    imeexceededn ransit

    cal ler

    eeps

    oing)

    *

    -1

    on ICMP

    ort

    unreachable

    cal ler

    s

    done)

    int

    recv_v4(int

    eq,struct imeval

    tv)

    {

    in t

    h len1 , len2 ,cmplen ;

    socklen_t

    len;

    ssize_t

    n;

    structp

    * ip,

    *hip;

    structcmp

    *icmp;

    struct

    dphdr

    *udp;

    alarm(3);

    f o r ( ; ; ) {

    ;gn

    =

    pr->salen;

    n

    =

    recvfrom(recvfd,

    ecvbuf,

    izeof(recvbuf),,

    pr->sarecv,

    len);

    i f ( n < 0 )

    i f

    (errno

    =

    EINTR)

    return(-3); l* alarm xpired

    /

    else

    4.80

    Network rogramming

    nd

    Management

  • 8/10/2019 Network Programmimg Unit 4

    80/85

    err_sys("ecvf

    om error")

    I

    Gettimeofday(tv,

    ULL);

    /*

    get

    time

    of

    packet

    arrival

    /

    ip

    =

    (struct

    p

    *)

    recvbuf;

    *

    start of

    lP header

    */

    h lenl

    =

    ip->ip_hl

    icmp_type

    =

    ICMP-TIMXCEED

    &

    icmp->icmp_code

    =

    lcMP_TIMXCEED_INTRANS)

    i f ( i c m p l e n < 8 + 2 0 + 8 )

    err_qui t (" icmplen%d) < 8 + 20 + 8" , cmplen);

    hip

    =

    (struct

    p

    *)

    (recvbuf

    + hlenl

    + 8);

    h l en2

    =

    h ip -> i p_h l

    iP-P

    ==

    IPPROTO-UDP

    &

    udp->uh_sPort

    :

    htons(sPort )

    &

    udp->uh_dport

    ==

    htons(dport

    seq))

    return(-2);

    /*

    we

    hit

    an

    intermediate

    outer

    */

    )

    e lse

    f

    ( icmp->icmp_type

    =

    ICMP-UNREACH)

    i f ( i c m p l e n < 8 + 2 0 + 8 )

    err_qui t (" icmplen

    %d) i p_h l

    iP-P= = IPPROTO-UDP &

    udp->uh_sport

    =

    htons(sport ) &

    udp->uh_dport

    ==

    htons(dport

    seq))

    i l

    ( icmp->icmp_code

    =

    ICMP-UNREACH-PORT)

    return(-1) ;

    "

    have eacheddest inat ion

    /

    else

    re t u rn ( i cm p-> i cm p_code ) ;

    *

    0 ,

    1 , 2 , . . . ' l

    )

    )

    else f

    (verbose)

    printf("

    (from

    %s: type

    :

    %d, code

    =

    o/od)\n",

    Sock_ntop_host(pr->sarecv,

    r->salen),

    icmp-

    cmp_type,cmp->

    cmp_code)

    )

    /*

    Some

    other

    ICMP error,

    ecvfrom$again

    */

    ) )

    Fig.4.47

    recv-v4

    unclion:

    readand

    process

    CMPv4

    nrcssages

    Set alarm

    and read each

    ICMP message

    An alarm

    s set

    or

    3

    secondsn

    the futureand

    he

    functionenters

    loop hat calls

    recvfrom, eading

    ach CMPv4

    message

    eturned n he

    aw socket.

    Get

    pointer

    o

    ICMP header

    ip

    points

    o

    the beginning f

    the Pv4

    header nd

    cmp

    points

    o thebeginning

    f the

    ICMPheader.

    Fig.4.48 hows hevarious eaders,ointers, nd engths sed y thecode'

    Advonced

    Sockels

    4.81

  • 8/10/2019 Network Programmimg Unit 4

    81/85

    n

    h len l

    icmplen

    hlen2

    lPv4

    header

    lPv4

    options

    ICMP4

    header

    lPv4

    header

    lPv4

    options

    UDP

    header

    o-40

    t

    8

    I

    udp

    lPv4 atagramhat

    generated

    he

    CMP

    error

    Fig,4.48 Headers,

    pointers

    and lengths in

    processing ICMPv4 erron

    Process

    CMP time exceeded

    n

    transit

    message

    If

    the ICMP

    messages a

    "

    time exceeded n transi t" message,

    t is

    possibilily

    a

    reply

    to one

    of our

    probes.

    hip

    points

    to

    the IPv4 header hat s returned n t he ICMP

    message,

    following

    the

    8

    byte

    ICMP header.

    dp

    points

    o the UDP

    header hat follows. If the

    ICMP

    message as

    generated

    y a UDP datagram nd f the sourceand destination

    ports

    of that

    datgramare the values hat are sent, hen his is a reply to out probe from an intermediate

    router.

    Process

    CMP

    port

    unreachablemessage

    If t he ICMP messages a

    "destination

    unreachable", hen the UDP

    header s returned

    in the ICMP

    message

    o see f

    the messages a response

    o our

    probe.

    f the ICMP code

    s

    "port

    unreachable"

    1

    is returned

    and

    the

    final destinati on s reached. f t he ICMP me ssage

    is from

    one of ourprobes, but

    it

    is not

    a

    "port

    unreachable" hen that ICMP

    port

    value s

    returned.

    Handle other ICMP messages

    All

    other ICMP

    messages

    re

    printed

    f the

    -v

    recv_v6

    s shown infig.4.49

    #include

    "trace.h"

    flag was

    specified.The

    next function

    *

    Return:

    3

    on imeout

    *

    -2

    on ICMP

    ime

    exceededn

    ransit

    cal ler

    eeps

    oing)

    *

    -'l

    on

    ICMP

    ort

    unreachable

    caller

    s

    done)

    int

    fzo

    ovtes o-40

    I

    8

    ip

    icmp

    t z o

    hip

    F--

    4.82

    Network rogramming

    ndManagement

  • 8/10/2019 Network Programmimg Unit 4

    82/85

    recv_v6(int

    eq,struct

    imeval

    tv)

    t

    #ifdef lPV6

    int

    hlen' | ,

    len2,cmP6len;

    ssize_t

    n;

    socklen_t

    len;

    struct

    p6_hdr

    * ip6,

    hiP6;

    structicmp6_hdr

    icmP6;

    struct dphdr

    *udp;

    alarm(3);

    f o r ( ; ; ) {

    len

    =

    pr->salen;

    n

    =

    recvfrom(recvfd,

    ecvbuf,

    izeof(recvbuf),

    ,

    pr->sarecv,

    len);

    i f ( n < 0 ) {

    i f

    (errno

    =

    EINTR)

    return(-3);

    /*

    alarm

    exPired

    /

    else

    err_sys("

    ecvfom

    error")

    )

    Gettimeofday(tv,

    ULL);

    /*

    get

    ime

    of

    packet

    rrival

    /

    ip6

    =

    (struct

    p6-hdr

    )

    recvbuf;

    /r

    start

    of

    lPv6header

    /

    hlenl

    =

    sizeof(struct

    p6_hd0;

    icmp6

    =

    (struct

    cmp6-hdr

    )

    (recvbuf hlenl) ;

    *

    ICMP

    dr

    */

    i l

    ( ( icmp6len n

    -

    hlenl)

    icmp6-type

    =

    ICMP6-TIME-EXCEEDED

    &

    icmp6->icmp6-code

    =

    ICMP6-TIME-EXCEED-TRANSIT)

    i f ( i c m p 6 l e n < 8 + 4 0 + 8 )

    err_quit(" icmp6len

    %d)