chapter three - a networking primer

90
Chapter Three - A Networking Primer Fundamentals of Data Fundamentals of Data Transfer 56 Transfer 56 Network Latency 56 Network Latency 56 Network Bandwidth Network Bandwidth 58 58 Network Reliability Network Reliability 58 58 Network Protocol 60 Network Protocol 60 The BSD Sockets The BSD Sockets Architecture 61 Architecture 61 Sockets and Ports Sockets and Ports 62 62 The Internet The Internet Protocol 65 Protocol 65

Upload: fedora

Post on 04-Jan-2016

20 views

Category:

Documents


2 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter Three  - A Networking Primer

Chapter Three - A Networking Primer

Fundamentals of Data Fundamentals of Data Transfer 56Transfer 56

• Network Latency 56Network Latency 56

• Network Bandwidth 58Network Bandwidth 58

• Network Reliability 58Network Reliability 58

• Network Protocol 60Network Protocol 60

Fundamentals of Data Fundamentals of Data Transfer 56Transfer 56

• Network Latency 56Network Latency 56

• Network Bandwidth 58Network Bandwidth 58

• Network Reliability 58Network Reliability 58

• Network Protocol 60Network Protocol 60

The BSD Sockets The BSD Sockets Architecture 61Architecture 61

• Sockets and Ports 62Sockets and Ports 62

• The Internet Protocol The Internet Protocol 6565

The BSD Sockets The BSD Sockets Architecture 61Architecture 61

• Sockets and Ports 62Sockets and Ports 62

• The Internet Protocol The Internet Protocol 6565

Page 2: Chapter Three  - A Networking Primer

Chapter Three - A Networking Primer

Introducing the Introducing the Internet Protocols for Internet Protocols for Net-VEs 65Net-VEs 65

• Transmission Control Transmission Control Protocol 67Protocol 67

• User Datagram User Datagram Protocol 67 IP Protocol 67 IP Broadcasting Using Broadcasting Using UDP 69UDP 69

• IP Multicasting 70IP Multicasting 70

Introducing the Introducing the Internet Protocols for Internet Protocols for Net-VEs 65Net-VEs 65

• Transmission Control Transmission Control Protocol 67Protocol 67

• User Datagram User Datagram Protocol 67 IP Protocol 67 IP Broadcasting Using Broadcasting Using UDP 69UDP 69

• IP Multicasting 70IP Multicasting 70

Selecting a Net-VE Selecting a Net-VE Protocol 75Protocol 75

• Using TCP/IP 77Using TCP/IP 77

• Using UDP/IP 77Using UDP/IP 77

• Using IP Broadcasting Using IP Broadcasting 8080

• Using IP Multicasting Using IP Multicasting 8282

Conclusion 82Conclusion 82

References 83References 83

Selecting a Net-VE Selecting a Net-VE Protocol 75Protocol 75

• Using TCP/IP 77Using TCP/IP 77

• Using UDP/IP 77Using UDP/IP 77

• Using IP Broadcasting Using IP Broadcasting 8080

• Using IP Multicasting Using IP Multicasting 8282

Conclusion 82Conclusion 82

References 83References 83

Page 3: Chapter Three  - A Networking Primer

OUTLINE•Fundamental principles behind computer Fundamental principles behind computer networking:networking:

– TCP/IP Layer ModelTCP/IP Layer Model– PotatoesPotatoes

∆ bandwidthbandwidth∆ latencylatency∆ reliabilityreliability

– Potatoes to the InternetPotatoes to the Internet– Network ProtocolNetwork Protocol

•BSD Sockets ArchitectureBSD Sockets Architecture– Sockets and PortsSockets and Ports– The Internet Protocol (IP)The Internet Protocol (IP)

•Fundamental principles behind computer Fundamental principles behind computer networking:networking:

– TCP/IP Layer ModelTCP/IP Layer Model– PotatoesPotatoes

∆ bandwidthbandwidth∆ latencylatency∆ reliabilityreliability

– Potatoes to the InternetPotatoes to the Internet– Network ProtocolNetwork Protocol

•BSD Sockets ArchitectureBSD Sockets Architecture– Sockets and PortsSockets and Ports– The Internet Protocol (IP)The Internet Protocol (IP)

Page 4: Chapter Three  - A Networking Primer

OUTLINE•Internet Protocols for Networked VE’sInternet Protocols for Networked VE’s::

– TCP/IPTCP/IP– UDP/IPUDP/IP– UDP broadcastingUDP broadcasting– IP multicastingIP multicasting

•Using C/C++Using C/C++

•Using JAVAUsing JAVA

•ConclusionConclusion

•Internet Protocols for Networked VE’sInternet Protocols for Networked VE’s::

– TCP/IPTCP/IP– UDP/IPUDP/IP– UDP broadcastingUDP broadcasting– IP multicastingIP multicasting

•Using C/C++Using C/C++

•Using JAVAUsing JAVA

•ConclusionConclusion

Page 5: Chapter Three  - A Networking Primer

Measures for Describing Network Behavior

•Network LatencyNetwork Latency

•Network BandwidthNetwork Bandwidth

•Network ReliabilityNetwork Reliability

•Network LatencyNetwork Latency

•Network BandwidthNetwork Bandwidth

•Network ReliabilityNetwork Reliability

Page 6: Chapter Three  - A Networking Primer

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

•Delay of transferDelay of transfer

•Reasons for network latencyReasons for network latency

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

– delays from the computers themselvesdelays from the computers themselves

– delays from the networkdelays from the network

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

•Delay of transferDelay of transfer

•Reasons for network latencyReasons for network latency

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

– delays from the computers themselvesdelays from the computers themselves

– delays from the networkdelays from the network

Page 7: Chapter Three  - A Networking Primer

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

•Rate of transferRate of transfer

•Available bandwidth determined by wire Available bandwidth determined by wire and hardwareand hardware

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

•Rate of transferRate of transfer

•Available bandwidth determined by wire Available bandwidth determined by wire and hardwareand hardware

Page 8: Chapter Three  - A Networking Primer

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

•Two categoriesTwo categories

• Dropping - discarded by the networkDropping - discarded by the network

• Corruption - content of data packets is changedCorruption - content of data packets is changed

•Reliability can vary widelyReliability can vary widely

•When reliability needed send acknowledgementWhen reliability needed send acknowledgement

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

•Two categoriesTwo categories

• Dropping - discarded by the networkDropping - discarded by the network

• Corruption - content of data packets is changedCorruption - content of data packets is changed

•Reliability can vary widelyReliability can vary widely

•When reliability needed send acknowledgementWhen reliability needed send acknowledgement

Page 9: Chapter Three  - A Networking Primer

NETWORK PROTOCOL•Describes the set of Describes the set of rules that two rules that two applications use to applications use to communicate to each communicate to each otherother

•Consists of three Consists of three components:components:

• Packet formatPacket format

• Packet semanticsPacket semantics

• Error behaviorError behavior

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

•Consists of three Consists of three components:components:

• Packet formatPacket format

• Packet semanticsPacket semantics

• Error behaviorError behavior

Page 10: Chapter Three  - A Networking Primer

PACKET FORMAT•Describes what each type of packet Describes what each type of packet looks likelooks like

•Tells the sender what to put in the Tells the sender what to put in the packetpacket

•Tells recipient how to parse the inbound Tells recipient how to parse the inbound packetpacket

•Describes what each type of packet Describes what each type of packet looks likelooks like

•Tells the sender what to put in the Tells the sender what to put in the packetpacket

•Tells recipient how to parse the inbound Tells recipient how to parse the inbound packetpacket

Page 11: Chapter Three  - A Networking Primer

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

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

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

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

Page 12: Chapter Three  - A Networking Primer

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

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

Page 13: Chapter Three  - A Networking Primer

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

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

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

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

Page 14: Chapter Three  - A Networking Primer

SOCKETS AND PORTS•Socket: a software representation of the Socket: a software representation of the endpoint to a communication channelendpoint to a communication channel

• can represent many different types of channelscan represent many different types of channels

• IP address + UDP/TCP + port numberIP address + UDP/TCP + port number

• 131.120.1.13, UDP, 51131.120.1.13, UDP, 51

• 131.120.1.13, TCP, 51131.120.1.13, TCP, 51

•Port: A specific numerical identifier for an Port: A specific numerical identifier for an individual applicationindividual application

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

• can represent many different types of channelscan represent many different types of channels

• IP address + UDP/TCP + port numberIP address + UDP/TCP + port number

• 131.120.1.13, UDP, 51131.120.1.13, UDP, 51

• 131.120.1.13, TCP, 51131.120.1.13, TCP, 51

•Port: A specific numerical identifier for an Port: A specific numerical identifier for an individual applicationindividual application

Page 15: Chapter Three  - A Networking Primer

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

• Protocol: How the operating systems exchange application Protocol: How the operating systems exchange application datadata

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

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

• Source host: Identifies which host is sending the dataSource host: Identifies which host is sending the data

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

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

• Protocol: How the operating systems exchange application Protocol: How the operating systems exchange application datadata

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

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

• Source host: Identifies which host is sending the dataSource host: Identifies which host is sending the data

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

Page 16: Chapter Three  - A Networking Primer

PORT NUMBERS•Provide foundation of open networkingProvide foundation of open networking

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

•Each application gets a port numberEach application gets a port number

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

•Over 65,000 valid port numbersOver 65,000 valid port numbers

• OS can support many applications at onceOS can support many applications at once

•Provide foundation of open networkingProvide foundation of open networking

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

•Each application gets a port numberEach application gets a port number

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

•Over 65,000 valid port numbersOver 65,000 valid port numbers

• OS can support many applications at onceOS can support many applications at once

Page 17: Chapter Three  - A Networking Primer

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

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

•Example:Example:

• port 80 is reserved for HTTPport 80 is reserved for HTTP

• port 25 is reserved for simple mail transfer protocolport 25 is reserved for simple mail transfer protocol

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

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

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

•Example:Example:

• port 80 is reserved for HTTPport 80 is reserved for HTTP

• port 25 is reserved for simple mail transfer protocolport 25 is reserved for simple mail transfer protocol

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

Page 18: Chapter Three  - A Networking Primer

INTERNET PROTOCOLS FORNETWORKED VE’s

•Common Internet ProtocolsCommon Internet Protocols

• Internet ProtocolInternet Protocol

• TCPTCP

• UDPUDP

•BroadcastingBroadcasting

•MulticastingMulticasting

•Common Internet ProtocolsCommon Internet Protocols

• Internet ProtocolInternet Protocol

• TCPTCP

• UDPUDP

•BroadcastingBroadcasting

•MulticastingMulticasting

Page 19: Chapter Three  - A Networking Primer

THE INTERNET PROTOCOL•Low-level protocol used by hosts and routers to Low-level protocol used by hosts and routers to ensure the packets travel from the source to the ensure the packets travel from the source to the destinationdestination

•Includes facilities for splitting the packets into Includes facilities for splitting the packets into small fragmentssmall fragments

• network links might not be able to support large network links might not be able to support large packetspackets

• used to reconstruct packets at other endused to reconstruct packets at other end

•Also includes time to live (TTL) fieldAlso includes time to live (TTL) field

• how many network hops may transfer the packethow many network hops may transfer the packet

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

•Includes facilities for splitting the packets into Includes facilities for splitting the packets into small fragmentssmall fragments

• network links might not be able to support large network links might not be able to support large packetspackets

• used to reconstruct packets at other endused to reconstruct packets at other end

•Also includes time to live (TTL) fieldAlso includes time to live (TTL) field

• how many network hops may transfer the packethow many network hops may transfer the packet

Page 20: Chapter Three  - A Networking Primer

INTERNET PROTOCOLS FOR NETWORKED VE’s

•TRANSMISSION CONTROL PROTOCOL (TCP)TRANSMISSION CONTROL PROTOCOL (TCP)

• Most common protocol in use todayMost common protocol in use today

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

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

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

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

•TRANSMISSION CONTROL PROTOCOL (TCP)TRANSMISSION CONTROL PROTOCOL (TCP)

• Most common protocol in use todayMost common protocol in use today

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

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

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

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

Page 21: Chapter Three  - A Networking Primer

USER DATAGRAM PROTOCOL (UDP)

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

•Differs from TCP in three respects:Differs from TCP in three respects:

• connection-less transmissionconnection-less transmission

• best-efforts delivery best-efforts delivery

• packet-based data semanticspacket-based data semantics

•Does not establish peer-to-peer connectionsDoes not establish peer-to-peer connections

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

•Differs from TCP in three respects:Differs from TCP in three respects:

• connection-less transmissionconnection-less transmission

• best-efforts delivery best-efforts delivery

• packet-based data semanticspacket-based data semantics

•Does not establish peer-to-peer connectionsDoes not establish peer-to-peer connections

Page 22: Chapter Three  - A Networking Primer

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

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

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

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

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

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

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

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

USER DATAGRAM PROTOCOL (UDP)

Page 23: Chapter Three  - A Networking Primer

USER DATAGRAM PROTOCOL (UDP) ADVANTAGES

•SimplicitySimplicity

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

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

•Does not maintain the illusion of a data streamDoes not maintain the illusion of a data stream

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

•SimplicitySimplicity

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

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

•Does not maintain the illusion of a data streamDoes not maintain the illusion of a data stream

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

Page 24: Chapter Three  - A Networking Primer

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

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

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

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

USER DATAGRAM PROTOCOL (UDP) ADVANTAGES

Page 25: Chapter Three  - A Networking Primer

USER DATAGRAM PROTOCOL (UDP) DISADVANTAGE FOR SOME VES

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

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

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

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

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

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

Page 26: Chapter Three  - A Networking Primer

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

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

This approach has two disadvantages:This approach has two disadvantages:

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

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

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

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

This approach has two disadvantages:This approach has two disadvantages:

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

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

Page 27: Chapter Three  - A Networking Primer

•UDP broadcasting provides a partial solution to these UDP broadcasting provides a partial solution to these issuesissues

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

•Useful for small net-VE’sUseful for small net-VE’s

•ExpensiveExpensive

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

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

•UDP broadcasting provides a partial solution to these UDP broadcasting provides a partial solution to these issuesissues

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

•Useful for small net-VE’sUseful for small net-VE’s

•ExpensiveExpensive

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

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

UDP BROADCASTING

Page 28: Chapter Three  - A Networking Primer

IP MULTICASTING•UDP broadcasting can only be used in a LAN UDP broadcasting can only be used in a LAN environmentenvironment

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

• receive packetreceive packet

• process the packetprocess the packet

• Multicasting is the solution to both of these concernsMulticasting is the solution to both of these concerns

•Appropriate for Internet use, as well as LAN useAppropriate for Internet use, as well as LAN use

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

•UDP broadcasting can only be used in a LAN UDP broadcasting can only be used in a LAN environmentenvironment

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

• receive packetreceive packet

• process the packetprocess the packet

• Multicasting is the solution to both of these concernsMulticasting is the solution to both of these concerns

•Appropriate for Internet use, as well as LAN useAppropriate for Internet use, as well as LAN use

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

Page 29: Chapter Three  - A Networking Primer

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

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

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

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

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

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

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

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

IP MULTICASTING

Page 30: Chapter Three  - A Networking Primer

IP MULTICASTING

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

•Provides:Provides:

• desirable network efficiency desirable network efficiency

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

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

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

•Provides:Provides:

• desirable network efficiency desirable network efficiency

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

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

Page 31: Chapter Three  - A Networking Primer

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

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

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

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

IP MULTICASTING

Page 32: Chapter Three  - A Networking Primer

IP MULTICASTING LIMITATIONS

•Limitations generally related to its infancyLimitations generally related to its infancy

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

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

•Limitations generally related to its infancyLimitations generally related to its infancy

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

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

Page 33: Chapter Three  - A Networking Primer

CODE•C/C++ and JAVA C/C++ and JAVA FOR:FOR:

• TCP/IPTCP/IP

• UDP/IPUDP/IP

• BROADCASTBROADCAST

• MULTICASTMULTICAST

•C/C++ and JAVA C/C++ and JAVA FOR:FOR:

• TCP/IPTCP/IP

• UDP/IPUDP/IP

• BROADCASTBROADCAST

• MULTICASTMULTICAST

Page 34: Chapter Three  - A Networking Primer

TCP/IP CLIENT SERVER MODEL

Network

CLIENT SERVER

SendsRequest

ReceivesRequest

CLIENT SERVER

Network

ReceivesReply

SendsReply

Courtesy of JAVA Networking and AWT API Superbible

Direct Connection Established

Direct Connection Established

Page 35: Chapter Three  - A Networking Primer

C / C++ TCP/IPC / C++ TCP/IPSOCKET SOCKET IMPLEMENTATION

CLIENT ACTIONS:CLIENT ACTIONS:

1. Obtain a socket1. Obtain a socket2. Connect to the server2. Connect to the server3. Communicate with server3. Communicate with server * Send data/requests* Send data/requests * Receive data/replys* Receive data/replys4. Close the socket4. Close the socket

SERVER ACTIONS:SERVER ACTIONS:

1. Obtain a socket1. Obtain a socket2. Bind the socket to a2. Bind the socket to a ‘ ‘well known’ portwell known’ port3. Receive connections 3. Receive connections from clientsfrom clients4. Communicate with clients4. Communicate with clients * Receive data/requests* Receive data/requests * Send data/replys* Send data/replys5. Close the socket5. Close the socket

Page 36: Chapter Three  - A Networking Primer

C / C++ TCP/IPSOCKET IMPLEMENTATION

CLIENT ACTIONS:CLIENT ACTIONS:

1. Obtain a socket1. Obtain a socket2. Connect to the server2. Connect to the server3. Communicate with server3. Communicate with server * Send data/requests* Send data/requests * Receive data/replys* Receive data/replys4. Close the socket4. Close the socket

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

Page 37: Chapter Three  - A Networking Primer

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;}

Page 38: Chapter Three  - A Networking Primer

C / C++ TCP/IPSOCKET IMPLEMENTATION

CLIENT ACTIONS:CLIENT ACTIONS:

1. Obtain a socket1. Obtain a socket2. 2. Connect to the serverConnect to the server3. Communicate with server3. Communicate with server * Send data/requests* Send data/requests * Receive data/replys* Receive data/replys4. Close the socket4. Close the socket

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

Page 39: Chapter Three  - A Networking Primer

C / C++ TCP/IPSOCKET IMPLEMENTATION

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

bzero((char *)&serverAddr, sizeof(serverAddr)); // Zero out allocated memoryserverAddr.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;

}

Page 40: Chapter Three  - A Networking Primer

1. Obtain a socket1. Obtain a socket2. Connect to the server2. Connect to the server3. Communicate with server3. Communicate with server * Send data/requests* Send data/requests * Receive data/replys* Receive data/replys4. Close the socket4. Close the socket

C / C++ TCP/IPSOCKET IMPLEMENTATION

CLIENT ACTIONS:CLIENT ACTIONS:COMMUNICATE W/ SERVER

* Place data to send into a buffer* Provide the buffer to the O/S along with socket ID for transmission

Page 41: Chapter Three  - A Networking Primer

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 socketperror("write"); // i.e. send the datareturn;

}

Page 42: Chapter Three  - A Networking Primer

C / C++ TCP/IPSOCKET IMPLEMENTATION

CLIENT ACTIONS:CLIENT ACTIONS:

1. Obtain a socket1. Obtain a socket2. Connect to the server2. Connect to the server3. Communicate with server3. Communicate with server * Send data/requests* Send data/requests * Receive data/replys* Receive data/replys4. Close the socket4. Close the socket

CLOSE THE SOCKET

* Invoke ‘close( ... )’ on the socket* Both sides must close their sockets to completely close the connection* code == > close(sock);

Page 43: Chapter Three  - A Networking Primer

1. Obtain a socket1. Obtain a socket2. Bind the socket to a2. Bind the socket to a ‘ ‘well known’ portwell known’ port3. Receive connections 3. Receive connections from clientsfrom clients4. Communicate with clients4. Communicate with clients * Recieve data/requests* Recieve data/requests * Send data/replys* Send data/replys5. Close the socket5. Close the socket

C / C++ TCP/IPSOCKET IMPLEMENTATION

SERVER ACTIONS:SERVER ACTIONS: BIND THE SOCKET TO A PORT

* Allocate an Internet Socket Address structure - sockaddr_in - contains address and port of the server* Bind the server to the socket

Page 44: Chapter Three  - A Networking Primer

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 portif (bind(sock, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) { perror("bind"); return;}

Page 45: Chapter Three  - A Networking Primer

1. Obtain a socket1. Obtain a socket2. Bind the socket to a2. Bind the socket to a ‘ ‘well known’ portwell known’ port3. Receive connections 3. Receive connections from clientsfrom clients4. Communicate with clients4. Communicate with clients * Recieve data/requests* Recieve data/requests * Send data/replys* Send data/replys5. Close the socket5. Close the socket

C / C++ TCP/IPSOCKET IMPLEMENTATION

SERVER ACTIONS:SERVER ACTIONS: RECEIVE CLIENT CONNECTIONS

* 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

Page 46: Chapter Three  - A Networking Primer

C / C++ TCP/IP SOCKET IMPLEMENTATION

int acceptSock = sock; // The original socket allocated by the server is used to // listen for and accept client connectionsstruct 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");

Page 47: Chapter Three  - A Networking Primer

1. Obtain a socket1. Obtain a socket2. Bind the socket to a2. Bind the socket to a ‘ ‘well known’ portwell known’ port3. Receive connections 3. Receive connections from clientsfrom clients4. Communicate with clients4. Communicate with clients * Receive data/requests* Receive data/requests * Send data/replys* Send data/replys5. Close the socket5. Close the socket

C / C++ TCP/IPSOCKET IMPLEMENTATION

SERVER ACTIONS:SERVER ACTIONS: COMMUNICATE WITH CLIENTS

* Allocate a buffer to place the data into* Read the data from the socket placing it into the buffer

Page 48: Chapter Three  - A Networking Primer

C / C++ TCP/IPSOCKET IMPLEMENTATION

int BUFFERLEN = 255; // Allocate buffer to place received data inchar 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 /* ... */}

Page 49: Chapter Three  - A Networking Primer

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

Page 50: Chapter Three  - A Networking Primer

JAVA TCP/IPJAVA TCP/IPSOCKET SOCKET IMPLEMENTATION

CLIENT ACTIONS:CLIENT ACTIONS:

1. Instantiate a Socket object1. Instantiate a Socket object2. Communicate with server2. Communicate with server * Send data/requests* Send data/requests * Receive data/replys* Receive data/replys3. Close the socket3. Close the socket

SERVER ACTIONS:SERVER ACTIONS:

1. Instantiate a ServerSocket1. Instantiate a ServerSocket objectobject2. Receive connections 2. Receive connections from clientsfrom clients3. Communicate with clients3. Communicate with clients * Recieve data/requests* Recieve data/requests * Send data/replys* Send data/replys4. Close the socket4. Close the socket

Page 51: Chapter Three  - A Networking Primer

JAVA TCP/IPSOCKET IMPLEMENTATION

CLIENT ACTIONS:CLIENT ACTIONS:

1. Instantiate a Socket object1. Instantiate a Socket object2. Communicate with server2. Communicate with server * Send data/requests* Send data/requests * Receive data/replys* Receive data/replys3. Close the socket3. Close the socket

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

Page 52: Chapter Three  - A Networking Primer

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 numbertry { sock = new Socket("netVE.nowhere.com", 13214);}

catch(IOException ioe) { System.out.println("Error opening socket: " + ioe.getMessage()); return;}

Page 53: Chapter Three  - A Networking Primer

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 numbertry { 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;

}

Page 54: Chapter Three  - A Networking Primer

1. Instantiate a Socket object1. Instantiate a Socket object2. Communicate with server2. Communicate with server * Send data/requests* Send data/requests * Receive data/replys* Receive data/replys3. Close the socket3. Close the socket

JAVA TCP/IPSOCKET IMPLEMENTATION

CLIENT ACTIONS:CLIENT ACTIONS:

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

Page 55: Chapter Three  - A Networking Primer

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());}

Page 56: Chapter Three  - A Networking Primer

JAVA TCP/IPSOCKET IMPLEMENTATION

CLIENT ACTIONS:CLIENT ACTIONS:

1. Instantiate a Socket object1. Instantiate a Socket object2. Communicate with server2. Communicate with server * Send data/requests* Send data/requests * Receive data/replys* Receive data/replys3. Close the socket3. Close the socket

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

Page 57: Chapter Three  - A Networking Primer

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.

Page 58: Chapter Three  - A Networking Primer

1. Instantiate a ServerSocket1. Instantiate a ServerSocket objectobject2. Receive connections 2. Receive connections from clientsfrom clients3. Communicate with clients3. Communicate with clients * Recieve data/requests* Recieve data/requests * Send data/replys* Send data/replys4. Close the socket4. Close the socket

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:SERVER ACTIONS:

Page 59: Chapter Three  - A Networking Primer

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 numbertry { acceptSock = new ServerSocket(13214);}

catch(IOException ioe) { System.out.println("Error opening server socket: " + ioe.getMessage()); return;}

Page 60: Chapter Three  - A Networking Primer

1. Instantiate a ServerSocket1. Instantiate a ServerSocket objectobject2. Receive connections 2. Receive connections from clientsfrom clients3. Communicate with clients3. Communicate with clients * Recieve data/requests* Recieve data/requests * Send data/replys* Send data/replys4. Close the socket4. Close the socket

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:SERVER ACTIONS:

Page 61: Chapter Three  - A Networking Primer

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

Page 62: Chapter Three  - A Networking Primer

1. Instantiate a ServerSocket1. Instantiate a ServerSocket objectobject2. Receive connections 2. Receive connections from clientsfrom clients3. Communicate with clients3. Communicate with clients * Recieve data/requests* Recieve data/requests * Send data/replys* Send data/replys4. Close the socket4. Close the socket

JAVA TCP/IPSOCKET IMPLEMENTATION

COMMUNICATE WITH CLIENTS

* 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

SERVER ACTIONS:SERVER ACTIONS:

Page 63: Chapter Three  - A Networking Primer

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());}

Page 64: Chapter Three  - A Networking Primer

UDP/IP COMMUNICATION MODEL

Network

Host A Host B

SendsData

ReceivesData

Host A Host B

Network

ReceivesData

SendsData

Courtesy of JAVA Networking and AWT API Superbible

No Connection Established

No Connection Established

Page 65: Chapter Three  - A Networking Primer

C / C++ UDP/IPSOCKET IMPLEMENTATION

STEPS TO IMPLEMENT A UDP/IP SOCKETSTEPS TO IMPLEMENT A UDP/IP SOCKET

1) Obtain a socket1) Obtain a socket2) Bind the socket to a ‘well known’ port2) Bind the socket to a ‘well known’ port3) Transmit Data3) Transmit Data4) Receive Data4) Receive Data5) Close the socket5) Close the socket

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

Page 66: Chapter Three  - A Networking Primer

C / C++ UDP/IPSOCKET IMPLEMENTATION

STEP 1: OBTAIN A SOCKETSTEP 1: OBTAIN A SOCKET

* Use the ‘socket( ... )’ function, ‘socket( ... )’ interfaces with * Use the ‘socket( ... )’ function, ‘socket( ... )’ interfaces with the O/S to create a socketthe O/S to create a socket* Arguments in the call to ‘socket( ... )’ determine the protocol* Arguments in the call to ‘socket( ... )’ determine the protocol and data stream semanticsand data stream semantics* Call to ‘socket( ... )’ returns an int that user can use to * Call to ‘socket( ... )’ returns an int that user can use to reference the socketreference the socket* No call to connect() is required as in TCP/IP because UDP/IP* No call to connect() is required as in TCP/IP because UDP/IP is connectionlessis connectionless

Page 67: Chapter Three  - A Networking Primer

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 socketsock = socket(PF_INET, SOCK_DGRAM, 0);if (sock == -1) { perror("socket"); return;}

Page 68: Chapter Three  - A Networking Primer

C / C++ UDP/IPSOCKET IMPLEMENTATION

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

* When data is first transmitted through a socket the O/S * When data is first transmitted through a socket the O/S binds a randomly chosen port to the socketbinds a randomly chosen port to the socket* It is better to bind the socket to a ‘well known’ port so other* It is better to bind the socket to a ‘well known’ port so other hosts know where to send datahosts know where to send data* Allocate an internet address structure to hold the sender’s IP* Allocate an internet address structure to hold the sender’s IP address and port number (sockaddr_in)address and port number (sockaddr_in)* Bind the socket to the port contained in the internet address* Bind the socket to the port contained in the internet address structurestructure

Page 69: Chapter Three  - A Networking Primer

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 memorylocalAddr.sin_family = PF_INET; // Use Internet addresses localAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Use any local IP addresslocalAddr.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;}

Page 70: Chapter Three  - A Networking Primer

C / C++ UDP/IPSOCKET IMPLEMENTATION

STEP 3: TRANSMIT DATASTEP 3: TRANSMIT DATA

* Write the data to be sent into a buffer* Write the data to be sent into a buffer* Allocate an internet address structure to contain destination* Allocate an internet address structure to contain destination IP address and portIP address and port* Transmit the data by calling sendto() function with data * Transmit the data by calling sendto() function with data buffer and internet address structure as argumentsbuffer and internet address structure as arguments* Note that unlike TCP/IP the size of the data need not be * Note that unlike TCP/IP the size of the data need not be transmitted, this is because datagram delivery semantics transmitted, this is because datagram delivery semantics ensure the entire buffer will be delivered as a unitensure the entire buffer will be delivered as a unit

Page 71: Chapter Three  - A Networking Primer

C / C++ UDP/IPSOCKET IMPLEMENTATION

int BUFFERLEN = 255; char buf[BUFFERLEN]; // Allocate buffer for datasprintf(buf, "hello!"); // Write data into the buffer

struct sockaddr_in destAddr; // The address/port of the remote endpointbzero((char *)&destAddr, sizeof(destAddr)); // zero out allocated memorydestAddr.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;}

Page 72: Chapter Three  - A Networking Primer

C / C++ UDP/IPSOCKET IMPLEMENTATION

STEP 4: RECIEVE DATASTEP 4: RECIEVE DATA

* Allocate a buffer to put received data in* Allocate a buffer to put received data in* Allocate an internet address structure to hold the sender’s* Allocate an internet address structure to hold the sender’s IP address and port numberIP address and port number* call recvfrom() function with data buffer and internet address* call recvfrom() function with data buffer and internet address structure as argumentsstructure as arguments

Page 73: Chapter Three  - A Networking Primer

C / C++ UDP/IPSOCKET IMPLEMENTATION

int BUFFERLEN = 255;char buf[BUFFERLEN]; // Buffer for incoming data

struct sockaddr_in srcAddr; // The address/port of senderbzero((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

Page 74: Chapter Three  - A Networking Primer

C / C++ UDP/IPSOCKET IMPLEMENTATION

STEP 5: CLOSE THE SOCKETSTEP 5: CLOSE THE SOCKET

* Remember, there is no connection to close* Remember, there is no connection to close* However, the socket should still be closed in order to free* However, the socket should still be closed in order to free resources that are no longer neededresources that are no longer needed* Other hosts have no way of knowing that the connection * Other hosts have no way of knowing that the connection has been closedhas been closed* code ==> close(sock);* code ==> close(sock);

Page 75: Chapter Three  - A Networking Primer

JAVA UDP/IPSOCKET IMPLEMENTATION

STEPS TO IMPLEMENT A UDP/IP SOCKETSTEPS TO IMPLEMENT A UDP/IP SOCKET

1) Obtain a socket1) Obtain a socket2) Transmit Data2) Transmit Data3) Receive Data3) Receive Data4) Close the socket4) Close the socket

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

Page 76: Chapter Three  - A Networking Primer

JAVA UDP/IPSOCKET IMPLEMENTATION

STEP 1: OBTAIN A SOCKETSTEP 1: OBTAIN A SOCKET

* Instantiate a DatagramSocket object* Instantiate a DatagramSocket object* Three constructors are available with arguments as follows* Three constructors are available with arguments as follows 1) Default, binds the socket to an arbitrary port1) Default, binds the socket to an arbitrary port 2) User provides the local port number2) User provides the local port number 3) User provides local port number and IP address3) User provides local port number and IP address

Page 77: Chapter Three  - A Networking Primer

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;}

Page 78: Chapter Three  - A Networking Primer

JAVA UDP/IPSOCKET IMPLEMENTATION

STEP 2: TRANSMIT DATASTEP 2: TRANSMIT DATA

* DatagramSockets send and receive DataGramPacket objects* DatagramSockets send and receive DataGramPacket objects* DataGramPackets contain...* DataGramPackets contain... - Data to send- Data to send - Destination IP address and port- Destination IP address and port* Build a DataGramPacket by...* Build a DataGramPacket by... - allocating a byte array output stream- allocating a byte array output stream - build a data output stream with the byte array output stream- build a data output stream with the byte array output stream - write data to the output stream- write data to the output stream - convert the output stream data to byte array form- convert the output stream data to byte array form - Create the DataGramPacket with the byte array, IP address- Create the DataGramPacket with the byte array, IP address and port number as argumentsand port number as arguments* Send the packet* Send the packet

Page 79: Chapter Three  - A Networking Primer

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());}

Page 80: Chapter Three  - A Networking Primer

JAVA UDP/IPSOCKET IMPLEMENTATION

STEP 3: RECEIVE DATASTEP 3: RECEIVE DATA

* Allocate a DataGramPacket to store the incoming packet* Allocate a DataGramPacket to store the incoming packet* Recieve the packet with the receive() function* Recieve the packet with the receive() function* Unpackage the DataGramPacket in a manner similiar to* Unpackage the DataGramPacket in a manner similiar to its constructionits construction

Page 81: Chapter Three  - A Networking Primer

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());}

Page 82: Chapter Three  - A Networking Primer

JAVA UDP/IPSOCKET IMPLEMENTATION

STEP 4: CLOSE THE SOCKETSTEP 4: CLOSE THE SOCKET

* Same rationale as in C/C++* Same rationale as in C/C++

Page 83: Chapter Three  - A Networking Primer

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.

Page 84: Chapter Three  - A Networking Primer

C / C++ UDP BROADCASTINGSOCKET IMPLEMENTATION

* UDP broadcasting is identical to UDP/IP unicast with two * UDP broadcasting is identical to UDP/IP unicast with two exceptionsexceptions 1) The destination address must be set to the broadcast pseudo1) The destination address must be set to the broadcast pseudo IP addressIP address

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

2) Before data can be broadcast on a socket the application2) Before data can be broadcast on a socket the application must register its intent to do somust register its intent to do so

int one = 1;int one = 1;setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one));setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one));

* SO_BROADCAST is a state variable, remains in force until* SO_BROADCAST is a state variable, remains in force until changedchanged* UDP sockets can receive both unicast and broadcast packets* UDP sockets can receive both unicast and broadcast packets

Page 85: Chapter Three  - A Networking Primer

JAVA UDP - BROADCASTINGSOCKET IMPLEMENTATION

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

- The application must initialize the DataGramPacket with- The application must initialize the DataGramPacket with the appropriate pseudo IP address the appropriate pseudo IP address

InetAddress destAddr = InetAddress.getByName(“255.255.255.255”)InetAddress destAddr = InetAddress.getByName(“255.255.255.255”)

Page 86: Chapter Three  - A Networking Primer

C / C++ MULTICASTINGSOCKET IMPLEMENTATION

* * TO TRANSMIT DATA:TO TRANSMIT DATA:

- Multicast transmission is nearly identical to UDP/IP. Make- Multicast transmission is nearly identical to UDP/IP. Make sure the packets are sent to a multicast addresssure the packets are sent to a multicast address - The SO_BROADCAST option need not be set- The SO_BROADCAST option need not be set - Can set the Time To Live field as shown below- Can set the Time To Live field as shown below

unsigned char ttl = 31;unsigned char ttl = 31;setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));

Page 87: Chapter Three  - A Networking Primer

* * TO RECEIVE DATA:TO RECEIVE DATA:

- The application must subscribe the socket to a multicast - The application must subscribe the socket to a multicast addressaddress - Subscribing to a multicast address is accomplished by calling- Subscribing to a multicast address is accomplished by calling setsockopt() with the IP_ADD_MEMBERSHIP optionsetsockopt() with the IP_ADD_MEMBERSHIP option

C / C++ MULTICASTINGSOCKET IMPLEMENTATION

struct ip_mreq joinAddr;struct ip_mreq joinAddr;

// Specify the multicast address to join// Specify the multicast address to joinjoinAddr.imr_multiaddr = inet_addr(“245.8.2.58”);joinAddr.imr_multiaddr = inet_addr(“245.8.2.58”);

// Specify which local IP address will do the multicast join// Specify which local IP address will do the multicast joinjoinAddr.imr_interface = INADDR_ANY;joinAddr.imr_interface = INADDR_ANY;

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

Page 88: Chapter Three  - A Networking Primer

* * TO RECEIVE DATA cont:TO RECEIVE DATA cont:

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

C / C++ MULTICASTINGSOCKET IMPLEMENTATION

struct ip_mreq joinAddr;struct ip_mreq joinAddr;

// Specify the multicast address to drop// Specify the multicast address to dropjoinAddr.imr_multiaddr = inet_addr(“245.8.2.58”);joinAddr.imr_multiaddr = inet_addr(“245.8.2.58”);

// Specify which local IP address will do the multicast drop// Specify which local IP address will do the multicast dropjoinAddr.imr_interface = INADDR_ANY;joinAddr.imr_interface = INADDR_ANY;

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

Page 89: Chapter Three  - A Networking Primer

* * TO TRANSMIT DATA:TO TRANSMIT DATA:

- To multicast from JAVA a MulticastSocket is used. Multicast- To multicast from JAVA a MulticastSocket is used. Multicast Sockets are are a sub-class of DatagramSocket and are Sockets are are a sub-class of DatagramSocket and are constructed in the same wayconstructed in the same way - To send to a multicast group simply specify a multicast - To send to a multicast group simply specify a multicast address as the destination in the DataGramPacketaddress as the destination in the DataGramPacket - send() function is the same- send() function is the same - specify time to live by...- specify time to live by...

JAVA MULTICASTINGSOCKET IMPLEMENTATION

sock.setTTL((byte)31);sock.setTTL((byte)31);// or specify it directly in the send call// or specify it directly in the send callsock.sendto(pack, (byte)12);sock.sendto(pack, (byte)12);

Page 90: Chapter Three  - A Networking Primer

* * TO RECEIVE DATA:TO RECEIVE DATA:

- Applications must join a multicast group, this is done with the- Applications must join a multicast group, this is done with the joinGroup() function of the MulticastSocket classjoinGroup() function of the MulticastSocket class

- Applications depart multicast groups with the leaveGroup()- Applications depart multicast groups with the leaveGroup() function of the MulticastSocket classfunction of the MulticastSocket class

JAVA MULTICASTINGSOCKET IMPLEMENTATION

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

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