Chapter three a networking primer
Download
1 / 90

Chapter Three - A Networking Primer - PowerPoint PPT Presentation


  • 62 Views
  • Uploaded on

Fundamentals of Data Transfer 56 Network Latency 56 Network Bandwidth 58 Network Reliability 58 Network Protocol 60. The BSD Sockets Architecture 61 Sockets and Ports 62 The Internet Protocol 65. Chapter Three - A Networking Primer. Introducing the Internet Protocols for Net-VEs 65

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Chapter Three - A Networking Primer' - gryta


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Chapter three a networking primer

Fundamentals of Data Transfer 56

Network Latency 56

Network Bandwidth 58

Network Reliability 58

Network Protocol 60

The BSD Sockets Architecture 61

Sockets and Ports 62

The Internet Protocol 65

Chapter Three - A Networking Primer


Chapter three a networking primer1

Introducing the Internet Protocols for Net-VEs 65

Transmission Control Protocol 67

User Datagram Protocol 67 IP Broadcasting Using UDP 69

IP Multicasting 70

Selecting a Net-VE Protocol 75

Using TCP/IP 77

Using UDP/IP 77

Using IP Broadcasting 80

Using IP Multicasting 82

Conclusion 82

References 83

Chapter Three - A Networking Primer


Outline
OUTLINE

  • Fundamental principles behind computer networking:

    • TCP/IP Layer Model

    • Potatoes

      • bandwidth

      • latency

      • reliability

    • Potatoes to the Internet

    • Network Protocol

  • BSD Sockets Architecture

    • Sockets and Ports

    • The Internet Protocol (IP)


  • Outline1
    OUTLINE

    • Internet Protocols for Networked VE’s:

      • TCP/IP

      • UDP/IP

      • UDP broadcasting

      • IP multicasting

  • Using C/C++

  • Using JAVA

  • Conclusion


  • Measures for describing network behavior
    Measures for Describing Network Behavior

    • Network Latency

    • Network Bandwidth

    • Network Reliability


    Network latency
    NETWORK LATENCY

    • Amount of time required to transfer a bit of data from one point to another

    • Delay of transfer

    • Reasons for network latency

      • speed of light delays (8.25ms of delay per time zone)

      • delays from the computers themselves

      • delays from the network


    Network bandwidth
    NETWORK BANDWIDTH

    • The rate at which the network can deliver data to the destination point

    • Rate of transfer

    • Available bandwidth determined by wire and hardware


    Network reliability
    NETWORK RELIABILITY

    • Measure of how much data is lost by the network during the journey

    • Two categories

      • Dropping - discarded by the network

      • Corruption - content of data packets is changed

    • Reliability can vary widely

    • When reliability needed send acknowledgement


    Network protocol
    NETWORK PROTOCOL

    • Describes the set of rules that two applications use to communicate to each other

    • Consists of three components:

      • Packet format

      • Packet semantics

      • Error behavior


    Packet format
    PACKET FORMAT

    • Describes what each type of packet looks like

    • Tells the sender what to put in the packet

    • Tells recipient how to parse the inbound packet


    Packet semantics
    PACKET SEMANTICS

    • Sender and recipient must agree on what the recipient can assume if it receives a particular packet

    • What actions the recipient should take in response to the packet


    Error behavior
    ERROR BEHAVIOR

    • Rules about how each endpoint should respond to various error scenarios


    The bsd sockets architecture
    The BSD Sockets Architecture

    • When an application sends a packet, the host must make sure that it gets sent to the right destination, and when a host receives a packet, it must make sure that it is delivered to the correct application. To achieve these two tasks, most hosts on the Internet use the Berkeley Software Distribution (BSD) Sockets network architecture to keep track of applications and network connections.

    • This architecture first gained wide acceptance in the Unix operating system, but today, it is implemented on virtually all of the major commercial operating systems on the market. The WinSock library used on Microsoft Windows 3.1/95/NT platforms is a derivative of the BSD interfaces [Quinn/Shute95].


    Sockets and ports
    SOCKETS AND PORTS

    • Socket: a software representation of the endpoint to a communication channel

      • can represent many different types of channels

      • IP address + UDP/TCP + port number

      • 131.120.1.13, UDP, 51

      • 131.120.1.13, TCP, 51

    • Port: A specific numerical identifier for an individual application


    Sockets
    SOCKETS

    • A socket identifies several pieces of information about a communication channel:

      • Protocol: How the operating systems exchange application data

      • Destination host: The destination host address(es) for packets sent on this socket

      • Destination application ID or port: Identifies the appropriate socket on the destination host

      • Source host: Identifies which host is sending the data

      • Local application ID/port: A 16 bit integer that identifies which application is sending data along this socket


    Port numbers
    PORT NUMBERS

    • Provide foundation of open networking

    • Like a set of post office box numbers for the protocol

    • Each application gets a port number

    • Port number + host address gives it a unique identifier to send and receive

    • Over 65,000 valid port numbers

      • OS can support many applications at once


    Port numbers1
    PORT NUMBERS

    • Port numbers 1 - 1024 are reserved for “well-known” applications/OS services

    • 1025 - 10,000 are registered for certain “well-known” protocols

    • Example:

      • port 80 is reserved for HTTP

      • port 25 is reserved for simple mail transfer protocol

      • port 1080 is used by SOCKS (network firewall security)


    Internet protocols for networked ve s
    INTERNET PROTOCOLS FORNETWORKED VE’s

    • Common Internet Protocols

      • Internet Protocol

      • TCP

      • UDP

    • Broadcasting

    • Multicasting


    The internet protocol
    THE INTERNET PROTOCOL

    • Low-level protocol used by hosts and routers to ensure the packets travel from the source to the destination

    • Includes facilities for splitting the packets into small fragments

      • network links might not be able to support large packets

      • used to reconstruct packets at other end

    • Also includes time to live (TTL) field

      • how many network hops may transfer the packet


    Internet protocols for networked ve s1
    INTERNET PROTOCOLS FOR NETWORKED VE’s

    • TRANSMISSION CONTROL PROTOCOL (TCP)

      • Most common protocol in use today

      • Layered on top of IP referred to as TCP/IP

      • Provides illusion of point to point connection to an application running on another machine

      • Each endpoint can regard a TCP/IP connection as a bi-directional stream of bytes between two endpoints

      • Application can detect when other end of connection has gone away/disconnected


    User datagram protocol udp
    USER DATAGRAM PROTOCOL (UDP)

    • The User Datagram Protocol (UDP) is a lightweight communication protocol

    • Differs from TCP in three respects:

      • connection-less transmission

      • best-efforts delivery

      • packet-based data semantics

    • Does not establish peer-to-peer connections


    User datagram protocol udp1
    USER DATAGRAM PROTOCOL (UDP)

    • Sender and recipient of do not keep any information about the state of the communication session between the two hosts

    • Simply provides best-efforts delivery, i.e. no guarantee that data is delivered reliably or in order

    • Endpoints do not maintain state information about the communication, UDP data is sent and received on a packet-by-packet basis

    • Datagrams must not be too big, because if they must be fragmented, some pieces might get lost in transit


    User datagram protocol udp advantages
    USER DATAGRAM PROTOCOL (UDP) ADVANTAGES

    • Simplicity

    • Does not include the overhead needed to detect reliability and maintain connection-oriented semantics

      • UDP packets require considerably less processing at the transmitting and receiving hosts

    • Does not maintain the illusion of a data stream

      • packets can be transmitted as soon as they are sent by the application instead of waiting in line behind other data in the stream; similarly, data can be delivered to the application as soon as it arrives at the receiving host instead of waiting in line behind missing data


    User datagram protocol udp advantages1
    USER DATAGRAM PROTOCOL (UDP) ADVANTAGES

    • Many operating systems impose limits on how many simultaneous TCP/IP connections they can support.

    • Operating system does not need to keep UDP connection information for every peer host, UDP/IP is more appropriate for large-scale distributed systems where each host communicates with many destinations simultaneously


    User datagram protocol udp disadvantage for some ves
    USER DATAGRAM PROTOCOL (UDP) DISADVANTAGE FOR SOME VES

    • When a socket is receiving data on a UDP port, it will receive packets sent to it by any host, whether it is participating in the application or not

    • This possibility can represent a security problem for some applications that do not robustly distinguish between expected and unexpected packets

    • For this reason, many network firewall administrators block UDP data from being sent to a protected host from outside the security perimeter


    Udp broadcasting
    UDP BROADCASTING

    • With UDP/IP, an application can direct a packet to be sent to one other application endpoint

    • Could send the same packet to multiple destinations by repeatedly calling sendto() (in C) or DatagramSocket.send() (in Java)

    • This approach has two disadvantages:

      • Excessive network bandwidth is required because the same packet is sent over the network multiple times

      • Each host must maintain an up-to-date list of all other application endpoints who are interested in its data


    Udp broadcasting1
    UDP BROADCASTING

    • UDP broadcasting provides a partial solution to these issues

    • Allows a single transmission to be delivered to all applications on a network who are receiving on a particular port

    • Useful for small net-VE’s

    • Expensive

      • every host on network must receive and process every broadcast packet

    • Not used for large or internet based VE’s (use IP Multicast)


    Ip multicasting
    IP MULTICASTING

    • UDP broadcasting can only be used in a LAN environment

    • Even if no application on that host is actually interested in receiving the packet each host on the LAN must:

      • receive packet

      • process the packet

    • Multicasting is the solution to both of these concerns

    • Appropriate for Internet use, as well as LAN use

    • Does not impose burdens on hosts that are not interested in receiving the multicast data


    Ip multicasting1
    IP MULTICASTING

    • IP addresses in the range 224.0.0.0 through 239.255.255.255 are designated as multicast addresses

    • The 224.*.*.* addresses are reserved for use by the management protocols on a LAN, and packets sent to the 239.*.*.* addresses are typically only sent to hosts within a single organization

    • Internet-based net-VE application should therefore use one or more random addresses in the 225.*.*.* to 238.*.*.* range

    • The sender transmits data to a multicast IP address, and a subscriber receives the packet if it has explicitly joined that address


    Ip multicasting2
    IP MULTICASTING

    • Rapidly emerging as the recommended way to build large-scale net-VEs over the Internet

    • Provides:

      • desirable network efficiency

      • allows the net-VE to partition different types of data by using multiple multicast addresses

    • Using a well-known multicast address, net-VE participants can announce their presence and learn about the presence of other participants


    Ip multicasting3
    IP MULTICASTING

    • Also an appropriate technique for discovering the availability of other net-VE resources such as terrain servers

    • These features make multicasting desirable even for LAN-based net-VEs.


    Ip multicasting limitations
    IP MULTICASTING LIMITATIONS

    • Limitations generally related to its infancy

    • Although an increasing number of routers are multicast-capable, many older routers are still not capable of handling multicast subscriptions

    • In the meantime, multicast-aware routers communicate directly with each other, “tunneling” data past the routers that cannot handle multicast data


    CODE

    • C/C++ and JAVA FOR:

      • TCP/IP

      • UDP/IP

      • BROADCAST

      • MULTICAST


    Tcp ip client server model

    Network

    Receives

    Request

    Sends

    Request

    CLIENT

    SERVER

    Network

    Receives

    Reply

    Sends

    Reply

    SERVER

    CLIENT

    TCP/IP CLIENT SERVER MODEL

    Direct Connection Established

    Direct Connection Established

    Courtesy of JAVA Networking and AWT API Superbible


    C c tcp ip socket implementation
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    CLIENT ACTIONS:

    SERVER ACTIONS:

    1. Obtain a socket

    2. Connect to the server

    3. Communicate with server

    * Send data/requests

    * Receive data/replys

    4. Close the socket

    1. Obtain a socket

    2. Bind the socket to a

    ‘well known’ port

    3. Receive connections

    from clients

    4. Communicate with clients

    * Receive data/requests

    * Send data/replys

    5. Close the socket


    C c tcp ip socket implementation1
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    OBTAIN A SOCKET

    * Use ‘socket( ... )’ function

    * ‘socket( ... )’ interfaces with

    the O/S to create a socket

    * Arguments in call to socket()

    determine the protocol and data

    stream semantics

    * ‘socket( ... )’ returns an int

    that the user can use to

    reference the socket

    CLIENT ACTIONS:

    1. Obtain a socket

    2. Connect to the server

    3. Communicate with server

    * Send data/requests

    * Receive data/replys

    4. Close the socket


    C c tcp ip socket implementation2
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    #include <stdio.h>

    #include <sys/types.h>

    #include <sys/socket.h>

    #include <netinet/in.h>

    int sock; // user reference to the socket

    // Allocate a socket function call parameters

    // PF_INET: Use the Internet family of Protocols

    // SOCK_STREAM: Provide reliable byte-stream semantics

    // 0: Use the default protocol (TCP) */

    sock = socket(PF_INET, SOCK_STREAM, 0);

    if (sock == -1) { // an error has occured

    perror("socket");

    return;

    }


    C c tcp ip socket implementation3
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    CONNECT TO THE SERVER

    * Allocate an Internet Socket Address

    - sockaddr_in

    - contains server address and port

    * Connect to the server

    - bind a free local port to the client’s

    socket

    - attempt to connect to the server

    specified in sockaddr_in

    - if connection is successful, it is

    initialized

    CLIENT ACTIONS:

    1. Obtain a socket

    2. Connect to the server

    3. Communicate with server

    * Send data/requests

    * Receive data/replys

    4. Close the socket


    C c tcp ip socket implementation4
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    struct sockaddr_in serverAddr; // The address and port of the server

    bzero((char *)&serverAddr, sizeof(serverAddr)); // Zero out allocated memory

    serverAddr.sin_family = PF_INET; // Use Internet addresses

    serverAddr.sin_addr.s_addr = inet_addr("10.25.43.9");

    // The inet_addr() function converts an IP address string into a four-byte

    // integer with one byte for each of the address values

    // htons() converts a 16-bit short integer into the network byte order so

    // that other hosts can interpret the integer even if they internally store

    // integers using a different byte order

    serverAddr.sin_port = htons(13214);

    // Connect to the remote host

    if (connect(sock, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) {

    perror("connect");

    return;

    }


    C c tcp ip socket implementation5
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    COMMUNICATE W/ SERVER

    CLIENT ACTIONS:

    1. Obtain a socket

    2. Connect to the server

    3. Communicate with server

    * Send data/requests

    * Receive data/replys

    4. Close the socket

    * Place data to send into a buffer

    * Provide the buffer to the O/S

    along with socket ID for

    transmission


    C c tcp ip socket implementation6
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    int BUFFERLEN = 255;

    char buf[BUFFERLEN]; // Allocate a buffer

    sprintf(buf, "%chello!", (char)strlen("hello!")); // Write data to buffer

    if (write(sock, buf, 1+strlen(buf)) == -1) { // Write buffer to socket

    perror("write"); // i.e. send the data

    return;

    }


    C c tcp ip socket implementation7
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    CLOSE THE SOCKET

    CLIENT ACTIONS:

    * Invoke ‘close( ... )’ on

    the socket

    * Both sides must close their

    sockets to completely close

    the connection

    * code == > close(sock);

    1. Obtain a socket

    2. Connect to the server

    3. Communicate with server

    * Send data/requests

    * Receive data/replys

    4. Close the socket


    C c tcp ip socket implementation8
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    BIND THE SOCKET TO A PORT

    SERVER ACTIONS:

    1. Obtain a socket

    2. Bind the socket to a

    ‘well known’ port

    3. Receive connections

    from clients

    4. Communicate with clients

    * Recieve data/requests

    * Send data/replys

    5. Close the socket

    * Allocate an Internet Socket

    Address structure

    - sockaddr_in

    - contains address and port of

    the server

    * Bind the server to the socket


    C c tcp ip socket implementation9
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    struct sockaddr_in serverAddr; // The address and port of the server

    bzero((char *)&serverAddr, sizeof(serverAddr)); // Zero out allocated memory

    serverAddr.sin_family = PF_INET; // Use Internet addresses

    // INADDR_ANY says that the operating system may choose to which local IP address to

    // attach the application. For most machines, which only have one address, this simply

    // chooses that address. The htonl() function converts a four-byte integer long integer into

    // the network byte order so that other hosts can interpret the integer even if they

    // internally store integers using a different byte order

    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    serverAddr.sin_port = htons(13214);

    // Bind the socket to the well-known port

    if (bind(sock, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) {

    perror("bind");

    return;

    }


    C c tcp ip socket implementation10
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    RECEIVE CLIENT CONNECTIONS

    SERVER ACTIONS:

    1. Obtain a socket

    2. Bind the socket to a

    ‘well known’ port

    3. Receive connections

    from clients

    4. Communicate with clients

    * Recieve data/requests

    * Send data/replys

    5. Close the socket

    * Listen for client connections

    - use ‘listen( ... )’

    - Tell O/S how many client

    connections can be queued

    * Call ‘accept( ... )’ to wait for

    a client to connect


    C c tcp ip socket implementation11
    C / C++ TCP/IP SOCKET IMPLEMENTATION

    int acceptSock = sock; // The original socket allocated by the server is used to

    // listen for and accept client connections

    struct sockaddr_in clientAddr; // allocate an address structure for the clients address

    listen(acceptSock, 4); // listen for connections

    while ((sock = accept(acceptSock, (struct sockaddr)&clientAddr, sizeof(clientAddr))) != -1) {

    // sock represents a connection to a client, clientAddr is the client's host address and port

    /* ... Process client connection ... */

    }

    // Only break out of loop if there is an error

    perror("accept");


    C c tcp ip socket implementation12
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    SERVER ACTIONS:

    COMMUNICATE WITH CLIENTS

    1. Obtain a socket

    2. Bind the socket to a

    ‘well known’ port

    3. Receive connections

    from clients

    4. Communicate with clients

    * Receive data/requests

    * Send data/replys

    5. Close the socket

    * Allocate a buffer to place the

    data into

    * Read the data from the socket

    placing it into the buffer


    C c tcp ip socket implementation13
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    int BUFFERLEN = 255; // Allocate buffer to place received data in

    char buf[BUFFERLEN];

    int byteCount = 0; // Total number of bytes read

    int n; // Number of bytes read this time

    while (((n = read(sock, buf+byteCount, BUFFERLEN-byteCount)) > 0) {

    byteCount += n;

    if (byteCount > buf[0]) {

    break;

    }

    }

    if (n < 0) { // error

    perror("read");

    return;

    }

    if (n == 0) { // Connection was closed

    /* ... */

    }


    C c tcp ip socket implementation14
    C / C++ TCP/IPSOCKET IMPLEMENTATION

    NOTES:

    * The server has actually opened two sockets,

    - One to receive connecting clients on

    - One to actually communicate to a specific client on

    * Provided code can only process one client at a time

    - threads can be used to process multiple client connections

    * read() and accept() calls block until data or a new client

    connection have arrived

    - This can be avoided using the select() function

    - Code is provided in the book


    Java tcp ip socket implementation
    JAVA TCP/IPSOCKET IMPLEMENTATION

    CLIENT ACTIONS:

    SERVER ACTIONS:

    1. Instantiate a Socket object

    2. Communicate with server

    * Send data/requests

    * Receive data/replys

    3. Close the socket

    1. Instantiate a ServerSocket

    object

    2. Receive connections

    from clients

    3. Communicate with clients

    * Recieve data/requests

    * Send data/replys

    4. Close the socket


    Java tcp ip socket implementation1
    JAVA TCP/IPSOCKET IMPLEMENTATION

    INSTANTIATE SOCKET OBJECT

    * Instantiating a socket creates a socket

    and connects it to the server

    * Two common constructors

    1) arguments are host name and port

    number

    2) arguments are host IP address and

    port number

    CLIENT ACTIONS:

    1. Instantiate a Socket object

    2. Communicate with server

    * Send data/requests

    * Receive data/replys

    3. Close the socket


    Java tcp ip socket implementation2
    JAVA TCP/IPSOCKET IMPLEMENTATION

    import java.net.Socket;

    import java.io.IOException;

    import java.io.DataInputStream;

    import java.io.DataOutputStream;

    Socket sock; // Declare the socket

    // Instantiate the socket using host name and port number

    try {

    sock = new Socket("netVE.nowhere.com", 13214);

    }

    catch(IOException ioe) {

    System.out.println("Error opening socket: " + ioe.getMessage());

    return;

    }


    Java tcp ip socket implementation3
    JAVA TCP/IPSOCKET IMPLEMENTATION

    import java.net.Socket;

    import java.io.IOException;

    import java.io.DataInputStream;

    import java.io.DataOutputStream;

    Socket sock; // Declare the socket

    // Retrieve the host’s internet address then instantaite the socket with

    // the IP address and port number

    try {

    InetAddress addr = InetAddress.getByName("10.25.43.9");

    sock = new Socket(addr, 13214);

    }

    catch(IOException ioe) {

    System.out.println("Error opening socket: " + ioe.getMessage());

    return;

    }


    Java tcp ip socket implementation4
    JAVA TCP/IPSOCKET IMPLEMENTATION

    COMMUNICATE WITH SERVER

    * Data is exchanged by reading and

    writing to input and output streams

    * Create a DataOutputStream

    * When creating the DataOutputStream

    tie it directly to the socket

    * Writing to the DataOutputStream then

    causes the data to automatically be

    transmitted to the server

    CLIENT ACTIONS:

    1. Instantiate a Socket object

    2. Communicate with server

    * Send data/requests

    * Receive data/replys

    3. Close the socket


    Java tcp ip socket implementation5
    JAVA TCP/IPSOCKET IMPLEMENTATION

    try{

    // Instantiate an output stream tied directly to the socket

    DataOutputStream oStream = new DataOutputStream(sock.getOutputStream());

    // write a string and an int to the output stream, i.e. transmit them to the server

    oStream.writeUTF("Hello!");

    oStream.writeInt(3);

    }

    catch(IOException ioe) {

    System.out.println("Write error: " + ioe.getMessage());

    }


    Java tcp ip socket implementation6
    JAVA TCP/IPSOCKET IMPLEMENTATION

    CLOSE THE SOCKET

    * Close the socket when finished

    communicating

    * Both client and server must close

    their sockets to completely tear

    down the connection

    * Server must also close down the

    ServerSocket when no more client

    connections are expected

    CLIENT ACTIONS:

    1. Instantiate a Socket object

    2. Communicate with server

    * Send data/requests

    * Receive data/replys

    3. Close the socket


    Java tcp ip socket implementation7
    JAVA TCP/IPSOCKET IMPLEMENTATION

    try{

    sock.close();

    }

    catch(IOException ioe) {

    System.out.println("Close error: " + ioe.getMessage());

    }

    // Again, close() needs to be called on both sides of the connection, and the server should

    // also be sure to close() the ServerSocket when it no longer wishes to accept client

    // connections.


    Java tcp ip socket implementation8
    JAVA TCP/IPSOCKET IMPLEMENTATION

    INSTANTIATE SERVERSOCKET

    * Instantiating a ServerSocket object

    creates a socket ready to accept client

    connections

    * Replaces the socket(), listen(), and

    bind() functions in C / C++

    * Three common constructors,

    arguments are...

    1) port number

    2) port number, listener backlog

    3) port number, listener backlog and

    IP address

    SERVER ACTIONS:

    1. Instantiate a ServerSocket

    object

    2. Receive connections

    from clients

    3. Communicate with clients

    * Recieve data/requests

    * Send data/replys

    4. Close the socket


    Java tcp ip socket implementation9
    JAVA TCP/IPSOCKET IMPLEMENTATION

    import java.net.ServerSocket;

    import java.net.Socket;

    import java.io.IOException;

    import java.io.DataInputStream;

    import java.io.DataOutputStream;

    ServerSocket acceptSock; // Declare the ServerSocket

    // Instantiate a ServerSocket using constructor that takes only the port number

    try {

    acceptSock = new ServerSocket(13214);

    }

    catch(IOException ioe) {

    System.out.println("Error opening server socket: " + ioe.getMessage());

    return;

    }


    Java tcp ip socket implementation10
    JAVA TCP/IPSOCKET IMPLEMENTATION

    RECEIVE CLIENT CONNECTIONS

    * Accept() call returns a socket that is the

    connection to a specific client

    - In other words the server has two

    sockets open just like C / C++

    * JAVA blocks on the accept() call

    - JAVA does not have the equivalent

    of a select() function to prevent this

    - Usual practice is to fork a thread for

    each client as well as one for the

    socket designated to recieve client

    connections

    SERVER ACTIONS:

    1. Instantiate a ServerSocket

    object

    2. Receive connections

    from clients

    3. Communicate with clients

    * Recieve data/requests

    * Send data/replys

    4. Close the socket


    Java tcp ip socket implementation11
    JAVA TCP/IPSOCKET IMPLEMENTATION

    Socket sock; // Declare a socket to represent the connection to a

    // specific client, i.e. the socket client and server will

    // communicate over

    // Call accept() on the ServerSocket to receive client connections,

    // when a connection is received a new socket is returned over which

    // the client and server will communicate

    while(true) {

    try {

    sock = acceptSock.accept();

    }

    catch(IOException ioe) {

    System.out.println("accept error: " + ioe.getMessage());

    break;

    }

    /* ... Process client connection ... */

    }

    // Only break out of while loop if there was an error


    Java tcp ip socket implementation12
    JAVA TCP/IPSOCKET IMPLEMENTATION

    COMMUNICATE WITH CLIENTS

    SERVER ACTIONS:

    1. Instantiate a ServerSocket

    object

    2. Receive connections

    from clients

    3. Communicate with clients

    * Recieve data/requests

    * Send data/replys

    4. Close the socket

    * Data is exchanged by reading and

    writing to input and output streams

    * Create a DataInputStream

    * When creating the DataInputStream

    tie it directly to the socket


    Java tcp ip socket implementation13
    JAVA TCP/IPSOCKET IMPLEMENTATION

    try{

    // Instantiate an input stream tied directly to the socket

    DataInputStream iStream = new DataInputStream(sock.getInputStream());

    // Read a string and an int from the input stream, i.e from the socket

    String helloString = iStream.readUTF();

    int three = iStream.readInt();

    }

    catch(IOException ioe) {

    System.out.println("Read error: " + ioe.getMessage());

    }


    Udp ip communication model
    UDP/IP COMMUNICATION MODEL

    Network

    Receives

    Data

    Sends

    Data

    Host A

    Host B

    No Connection Established

    Network

    Receives

    Data

    Sends

    Data

    Host B

    Host A

    No Connection Established

    Courtesy of JAVA Networking and AWT API Superbible


    C c udp ip socket implementation
    C / C++ UDP/IPSOCKET IMPLEMENTATION

    STEPS TO IMPLEMENT A UDP/IP SOCKET

    1) Obtain a socket

    2) Bind the socket to a ‘well known’ port

    3) Transmit Data

    4) Receive Data

    5) Close the socket

    * Above process is ‘a way’ not the only way


    C c udp ip socket implementation1
    C / C++ UDP/IPSOCKET IMPLEMENTATION

    STEP 1: OBTAIN A SOCKET

    * Use the ‘socket( ... )’ function, ‘socket( ... )’ interfaces with

    the O/S to create a socket

    * Arguments in the call to ‘socket( ... )’ determine the protocol

    and data stream semantics

    * Call to ‘socket( ... )’ returns an int that user can use to

    reference the socket

    * No call to connect() is required as in TCP/IP because UDP/IP

    is connectionless


    C c udp ip socket implemenatation
    C / C++ UDP/IPSOCKET IMPLEMENATATION

    #include <sys/types.h>

    #include <sys/socket.h>

    #include <netinet/in.h>

    int sock; // Declare an int to hold a reference to

    // a socket

    // arguments in call to socket are as follows...

    // PF_INET: Use the Internet family of Protocols

    // SOCK_DGRAM: Provide best-efforts packet semantics

    // 0: Use the default protocol (UDP)

    // create/open the socket

    sock = socket(PF_INET, SOCK_DGRAM, 0);

    if (sock == -1) {

    perror("socket");

    return;

    }


    C c udp ip socket implementation2
    C / C++ UDP/IPSOCKET IMPLEMENTATION

    STEP 2: BIND SOCKET TO A ‘WELL KNOWN’ PORT

    * When data is first transmitted through a socket the O/S

    binds a randomly chosen port to the socket

    * It is better to bind the socket to a ‘well known’ port so other

    hosts know where to send data

    * Allocate an internet address structure to hold the sender’s IP

    address and port number (sockaddr_in)

    * Bind the socket to the port contained in the internet address

    structure


    C c udp ip socket implementation3
    C / C++ UDP/IPSOCKET IMPLEMENTATION

    struct sockaddr_in localAddr; // Allocate an internet address structure

    // for the address/port of the local endpoint

    bzero((char *)&localAddr, sizeof(localAddr)); // zero out allocated memory

    localAddr.sin_family = PF_INET; // Use Internet addresses

    localAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Use any local IP address

    localAddr.sin_port = htons(13214); // Port that others can send to

    // Bind the socket to the well-known port

    if (bind(sock, (struct sockaddr *)&localAddr, sizeof(localAddr)) == -1) {

    perror("bind");

    return;

    }


    C c udp ip socket implementation4
    C / C++ UDP/IPSOCKET IMPLEMENTATION

    STEP 3: TRANSMIT DATA

    * Write the data to be sent into a buffer

    * Allocate an internet address structure to contain destination

    IP address and port

    * Transmit the data by calling sendto() function with data

    buffer and internet address structure as arguments

    * Note that unlike TCP/IP the size of the data need not be

    transmitted, this is because datagram delivery semantics

    ensure the entire buffer will be delivered as a unit


    C c udp ip socket implementation5
    C / C++ UDP/IPSOCKET IMPLEMENTATION

    int BUFFERLEN = 255;

    char buf[BUFFERLEN]; // Allocate buffer for data

    sprintf(buf, "hello!"); // Write data into the buffer

    struct sockaddr_in destAddr; // The address/port of the remote endpoint

    bzero((char *)&destAddr, sizeof(destAddr)); // zero out allocated memory

    destAddr.sin_family = PF_INET; // Use Internet addresses

    destAddr.sin_addr.s_addr = inet_addr("10.25.43.9");

    destAddr.sin_port = htons(13214);

    // Send data to the specified destination

    if (sendto(sock, buf, strlen(buf) + 1, 0,

    (struct sockaddr *)&destAddr, sizeof(destAddr)) != strlen(buf)) {

    perror("sendto");

    return;

    }


    C c udp ip socket implementation6
    C / C++ UDP/IPSOCKET IMPLEMENTATION

    STEP 4: RECIEVE DATA

    * Allocate a buffer to put received data in

    * Allocate an internet address structure to hold the sender’s

    IP address and port number

    * call recvfrom() function with data buffer and internet address

    structure as arguments


    C c udp ip socket implementation7
    C / C++ UDP/IPSOCKET IMPLEMENTATION

    int BUFFERLEN = 255;

    char buf[BUFFERLEN]; // Buffer for incoming data

    struct sockaddr_in srcAddr; // The address/port of sender

    bzero((char *)&destAddr, sizeof(srcAddr)); // zero out allocated memory

    // Receive data sent to the UDP port

    if (recvfrom(sock, buf, sizeof(buf), 0,

    (struct sockaddr *)&srcAddr, sizeof(srcAddr)) == -1) {

    perror("recvfrom");

    return;

    }

    // Sender's address stored in srcAddr structure


    C c udp ip socket implementation8
    C / C++ UDP/IPSOCKET IMPLEMENTATION

    STEP 5: CLOSE THE SOCKET

    * Remember, there is no connection to close

    * However, the socket should still be closed in order to free

    resources that are no longer needed

    * Other hosts have no way of knowing that the connection

    has been closed

    * code ==> close(sock);


    Java udp ip socket implementation
    JAVA UDP/IPSOCKET IMPLEMENTATION

    STEPS TO IMPLEMENT A UDP/IP SOCKET

    1) Obtain a socket

    2) Transmit Data

    3) Receive Data

    4) Close the socket

    * Above process is ‘a way’ not the only way


    Java udp ip socket implementation1
    JAVA UDP/IPSOCKET IMPLEMENTATION

    STEP 1: OBTAIN A SOCKET

    * Instantiate a DatagramSocket object

    * Three constructors are available with arguments as follows

    1) Default, binds the socket to an arbitrary port

    2) User provides the local port number

    3) User provides local port number and IP address


    Java udp ip socket implemenatation
    JAVA UDP/IPSOCKET IMPLEMENATATION

    import java.net.DatagramSocket;

    import java.io.IOException;

    import java.io.ByteArrayInputStream;

    import java.io.ByteArrayOutputStream;

    import java.io.DataInputStream;

    import java.io.DataOutputStream;

    DatagramSocket sock; // Declare a Datagram socket

    try {

    // Omit the constructor argument to bind to an arbitrary local port

    sock = new DatagramSocket(13214); // Bind to local UDP port 13214

    }

    catch(IOException ioe) {

    System.out.println("Error creating socket: " + ioe.getMessage());

    return;

    }


    Java udp ip socket implementation2
    JAVA UDP/IPSOCKET IMPLEMENTATION

    STEP 2: TRANSMIT DATA

    * DatagramSockets send and receive DataGramPacket objects

    * DataGramPackets contain...

    - Data to send

    - Destination IP address and port

    * Build a DataGramPacket by...

    - allocating a byte array output stream

    - build a data output stream with the byte array output stream

    - write data to the output stream

    - convert the output stream data to byte array form

    - Create the DataGramPacket with the byte array, IP address

    and port number as arguments

    * Send the packet


    Java udp ip socket implementation3
    JAVA UDP/IPSOCKET IMPLEMENTATION

    try{

    // Build the IP address and port

    InetAddress destAddr = InetAddress.getByName("10.25.43.9");

    int destPort = 13214;

    // Configure the data stream

    ByteArrayOutputStream boStream = new ByteArrayOutputStream();

    DataOutputStream oStream = new DataOutputStream(boStream);

    oStream.writeUTF("Hello!"); // write data to the stream

    oStream.writeInt(3);

    byte[] dataBytes = boStream.getByteArray(); // convert stream to byte array

    DatagramPacket pack = // Construct the DataGramPacket

    new DatagramPacket(dataBytes, dataBytes.length, destAddr, destPort)

    sock.send(pack);

    }

    catch(IOException ioe) {

    System.out.println("Send error: " + ioe.getMessage());

    }


    Java udp ip socket implementation4
    JAVA UDP/IPSOCKET IMPLEMENTATION

    STEP 3: RECEIVE DATA

    * Allocate a DataGramPacket to store the incoming packet

    * Recieve the packet with the receive() function

    * Unpackage the DataGramPacket in a manner similiar to

    its construction


    Java udp ip socket implementation5
    JAVA UDP/IPSOCKET IMPLEMENTATION

    try{

    // Build structures to hold incoming information

    byte[] dataBytes = new byte[255];

    DatagramPacket pack = new DatagramPacket(dataBytes, dataBytes.length);

    // Recieve the incoming packet

    sock.receive(pack); // Sender information available in

    // pack.getAddress() and pack.getPort()

    // Unpackage the DataGramPacket

    ByteArrayInputStream biStream = new ByteArrayOutputStream();

    DataInputStream iStream = new DataInputStream(biStream);

    String helloString = iStream.readUTF();

    int three = iStream.readInt();

    }

    catch(IOException ioe) {

    System.out.println("Receive error: " + ioe.getMessage());

    }


    Java udp ip socket implementation6
    JAVA UDP/IPSOCKET IMPLEMENTATION

    STEP 4: CLOSE THE SOCKET

    * Same rationale as in C/C++


    Java udp ip socket implementation7
    JAVA UDP/IPSOCKET IMPLEMENTATION

    try{

    sock.close();

    }

    catch(IOException ioe) {

    System.out.println("Close error: " + ioe.getMessage());

    }

    // Again, close() needs to be called on both applications, and an

    // application receives no indication that a remote application has

    // closed its UDP socket.


    C c udp broadcasting socket implementation
    C / C++ UDP BROADCASTINGSOCKET IMPLEMENTATION

    * UDP broadcasting is identical to UDP/IP unicast with two

    exceptions

    1) The destination address must be set to the broadcast pseudo

    IP address

    destAddr.sin_addr.s_addr = inet_addr(“255.255.255.255”)

    2) Before data can be broadcast on a socket the application

    must register its intent to do so

    int one = 1;

    setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one));

    * SO_BROADCAST is a state variable, remains in force until

    changed

    * UDP sockets can receive both unicast and broadcast packets


    Java udp broadcasting socket implementation
    JAVA UDP - BROADCASTINGSOCKET IMPLEMENTATION

    * UDP broadcasting is identical to UDP/IP with 1 exception

    - The application must initialize the DataGramPacket with

    the appropriate pseudo IP address

    InetAddress destAddr = InetAddress.getByName(“255.255.255.255”)


    C c multicasting socket implementation
    C / C++ MULTICASTINGSOCKET IMPLEMENTATION

    * TO TRANSMIT DATA:

    - Multicast transmission is nearly identical to UDP/IP. Make

    sure the packets are sent to a multicast address

    - The SO_BROADCAST option need not be set

    - Can set the Time To Live field as shown below

    unsigned char ttl = 31;

    setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));


    C c multicasting socket implementation1
    C / C++ MULTICASTINGSOCKET IMPLEMENTATION

    * TO RECEIVE DATA:

    - The application must subscribe the socket to a multicast address

    - Subscribing to a multicast address is accomplished by calling

    setsockopt() with the IP_ADD_MEMBERSHIP option

    struct ip_mreq joinAddr;

    // Specify the multicast address to join

    joinAddr.imr_multiaddr = inet_addr(“245.8.2.58”);

    // Specify which local IP address will do the multicast join

    joinAddr.imr_interface = INADDR_ANY;

    setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &joinAddr, sizeof(joinAddr))


    C c multicasting socket implementation2
    C / C++ MULTICASTINGSOCKET IMPLEMENTATION

    * TO RECEIVE DATA cont:

    - To cancel a multicast subscription call setsockopt() with the

    IP_DROP_MEMBERSHIP option

    struct ip_mreq joinAddr;

    // Specify the multicast address to drop

    joinAddr.imr_multiaddr = inet_addr(“245.8.2.58”);

    // Specify which local IP address will do the multicast drop

    joinAddr.imr_interface = INADDR_ANY;

    setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, &joinAddr, sizeof(joinAddr))


    Java multicasting socket implementation
    JAVA MULTICASTINGSOCKET IMPLEMENTATION

    * TO TRANSMIT DATA:

    - To multicast from JAVA a MulticastSocket is used. Multicast

    Sockets are are a sub-class of DatagramSocket and are

    constructed in the same way

    - To send to a multicast group simply specify a multicast

    address as the destination in the DataGramPacket

    - send() function is the same

    - specify time to live by...

    sock.setTTL((byte)31);

    // or specify it directly in the send call

    sock.sendto(pack, (byte)12);


    Java multicasting socket implementation1
    JAVA MULTICASTINGSOCKET IMPLEMENTATION

    * TO RECEIVE DATA:

    - Applications must join a multicast group, this is done with the

    joinGroup() function of the MulticastSocket class

    - Applications depart multicast groups with the leaveGroup()

    function of the MulticastSocket class

    sock.joinGroup(InetAddress.getByName(“245.8.2.58”);

    sock.leaveGroup(InetAddress.getByName(“245.8.2.58”);


    ad