Distributed Real-Time Control Systems Module 26 Sockets 1
Network Programming with Sockets Sockets are probably the most widely used objects in programming networked communications. What is a socket? To the kernel, a socket is an endpoint of communication: IP address, port number, and protocol (TCP, UDP, etc). To an application, a socket is a file descriptor that lets the application read/write from/to the network Clients and servers communicate with each by reading from and writing to socket. 2
The Ethernet Frame-based Technology Ethernet stations communicate by sending each other data packets. Each Ethernet station is given a single 48-bit MAC address, which is used both to specify the destination and the source of each data packet. 3
The OSI stack model APDU Application Application Protocol Application 7 PPDU Presentation Presentation Protocol Presentation 6 SPDU Session Session Protocol Session 5 TPDU Transport Trasport Protocol Host-Router communication boundary Transport 4 packet Network Network Network Network 3 Frame Data Link Data Link Data Link Data Link 2 Bit Physical Physical Physical Physical 1 Host-Router internal protocol 4
IP Addressing There are two versions of an IP address : IPv4 and IPv6. Because of its prevalence, "IP address" typically refers to those defined by IPv4. Using reserved values for the first octet, network addresses are broken into classes: Class A very large networks (up to 2 24 hosts) Class B large networks (up to 2 16 hosts) Class C small networks (up to 255 hosts) Class D multi-cast messages to multiple hosts Class E addresses not allocated and reserved. 5
IP Classes 7 24 Class A: 0 Network ID Host ID 14 16 Class B: 1 0 Network ID Host ID 21 8 Class C: 1 1 0 Network ID Host ID 28 Class D (multicast): 1 1 1 0 Multicast address Class E (reserv ed): 1 1 1 1 0 unused Class Range within 1st octet Network ID Host ID 27 Possible number of networks Possible number of hosts A 1-126 a b.c.d. 126 16,777,214 B 128-191 a.b c.d 16,384 65,534 C 192-223 a.b.c d 2,097,151 254 6
Special Addresses Adapter Loopback 127.0.0.1 Private addresses (will not be routed) 10.0.0.0-10.255.255.255 172.16.0.0-172.31.255.255 192.168.0.0-192.168.255.255 7
Subnet Masking Subnetwork or Subnet is a range of logical addresses within the address space that is assigned to an organization. Subnetworking simplifies routing. Dot-decimal Address Full Network Address 192.168.5.10 Subnet Mask 255.255.255.0 Network Portion 192.168.5.0 Host Portion 0.0.0.10 Binary 11000000.10101000.000001 01.00001010 11111111.11111111.111111 11.00000000 11000000.10101000.000001 01.00000000 00000000.00000000.000000 00.00001010 8
Address Resolution The Address Resolution Protocol (ARP) is a method for finding a host s hardware address when only its network layer address is known. E.g. IP addresses to MAC addresses. ARP is used in four cases of two hosts communicating: 1. When two hosts are on the same network and one desires to send a packet to the other 2. When two hosts are on different networks and must use a gateway/router to reach the other host 3. When a router needs to forward a packet for one host through another router 4. When a router needs to forward a packet from one host to the destination host on the same network 9
Sockets A socket is an endpoint of communication: IP address, port number, and protocol (TCP, UDP, etc). TCP (or Stream) Sockets Connection oriented, require handshake Client contacts Server to establish connection. Server provides a private connection to client. UDP (or Datagram) Sockets Connectionless, low overhead. Data is sent directly to destination. No handshake: data may be lost. 10
Connection-Oriented Model The connection-oriented model is implemented with Stream Sockets using the TCP protocol. TCP provides a variety or error correction and performance features for transmission of byte streams. Implements a client-server architecture. 11
Connectionless-Oriented Model The connectionless model uses UDP protocol with no guarantee of delivery. UDP packets may arrive out of order, multiple times, or not at all. UDP has considerably less overhead than TCP Implements a peer-to-peer architecture. 12
Connectionless-Oriented Model (UDP) Server Process socket() bind() Client Process socket() bind() read_from() write_to() request response write_to() read_from() close() close() 13
Datagram (UDP) Socket Primitives socket() creates a new socket, and allocates system resources to it. bind() is the process to associate a socket with a specified local port number and IP address. send_to()/write_to, recv_from()/read_from(), are used for sending and receiving data to/from a remote socket. 14
Boost Datagram Sockets ip::udp::endpoint - identifies an address, port and protocol for communication. ip::udp::resolver (cliente side) retrieves a suitable communication endpoint from a server. ip::udp::socket creates a socket associated to an endpoint socket::receive_from() waits for some data from any client socket::send_to() sends data to a specific client 15
Boost Synchronous UDP Example #include <iostream> //SYNC_UDP_SERVER #include <boost/asio.hpp> using namespace boost::asio; using ip::udp; int main() { io_service io; auto ep = udp::endpoint(udp::v4(),10000); std::cout << Receiving at: << ep << std::endl; udp::socket s(io,ep)); char buf[1] = {0}; while (buf[0]!= q ) { udp::endpoint client; //client endpoint retrieved on receive_from s.receive_from(buffer(buf, 1), client); if( buf[0]!= q ) s.send_to(buffer( Hello World ), client); else s.send_to(buffer( q ), client); } } #include <iostream> //SYNC_UDP_CLIENT #include <boost/asio.hpp> using namespace boost::asio; using ip::udp; using query = udp::resolver::query; int main() { io_service io; udp::resolver r(io); query q(udp::v4(),"127.0.0.1","10000"); udp::endpoint ep = *r.resolve(q); udp::socket s(io); s.open(udp::v4()); char buf[128] = {0}; do { std::cin.getline(buf,128); s.send_to(buffer(buf,1), ep); //send 1st char size_t n = s.receive_from(buffer(buf, 128),ep); std::cout.write(buf, n-1); } while( buf[0]!= q ) } 16
Notes on Previous Code The example client opens a socket to the server machine and loops on reading data from cin, sending a char to make contact with server, wait server reply and prints the reply. When the reply start with character q, it exits. The example server waits for messages of arbitrary clients and sends back the message Hello World, unless the first character of the message is q. In that case it also sends back q and exits. This example does not check for errors. Functions send_to and receive_from have overloads to check for errors: socket.send_to(buffer, end_point, flags, error_code) socket.receive_to(buffer, end_point, flags, error_code) 17
Connection Oriented Model Server Listening socket Welcomes some initial contact from a client Connection socket It is created at initial contact of client New socket that is dedicated to the particular client Client Client socket Specify the address of the server process, namely, the IP address of the server and the port number of the process 18
Connection-Oriented Model Server Process socket() Client Process socket() bind() listen() accept() get a blocked client read() write() read() 3-way handshake client request server response close notification connect() write() read() close() close() 19
Socket Primitives socket() creates a new socket and allocates system resources to it. bind() is typically used on the server side, and associates a socket with a socket address structure, i.e. a specified local port number and IP address. listen() is used on the server side, and causes a bound TCP socket to enter listening state. connect() is used on the client side. Attempts to establish a new TCP connection. accept() is used on the server side. It accepts a received incoming attempt to create a new TCP connection from the remote client, and creates a new socket associated with the socket address pair of this connection. write() and read() are used for sending and receiving data to/from a remote socket. 20
Boost Stream Sockets Important classes ip::tcp::acceptor - binds a listening socket to accept cliente requests ip::tcp::endpoint sets address and port pair for accept cliente requests ip::tcp::resolver retrieves a address and port pair for communication ip::tcp::socket - a socket associated to an endpoint Important functions acceptor::accept() accepts connections from a client ip::tcp::connect() tries to connect to a server. ip::tcp::read() waits until some data is received ip::tcp::write() write to socket 21
Boost Synchronous TCP Example #include <iostream> //SYNC_TCP_SERVER.CPP #include <boost/asio.hpp> using namespace boost::asio; using ip::tcp; int main() { io_service io; boost::system::error_code ec; char buf[128]; auto ep = tcp::endpoint(tcp::v4(),10000); std::cout << Listening at: << ep << std::endl; tcp::acceptor a(io, ep); for (;;) { tcp::socket s(io); //create new listening socket a.accept(s); //wait client to connect for(;;) { //got a client size_t n = s.read_some(buffer(buf,128), ec); if(ec) break; write(s, buffer(buf,n), ec); if(ec) break; } //kills connection } } #include <iostream> //SYNC_TCP_CLIENT.CPP #include <boost/asio.hpp> using namespace boost::asio; using ip::tcp; int main() { io_service io; boost::system::error_code err; char buf[128]; tcp::resolver r(io); //find endpoints from address tcp::resolver::query q( 127.0.0.1, 10000 ); tcp::resolver::iterator server = r.resolve(q); tcp::socket s(io); s.connect(*server, err); //connect and wait for (;;) { std::cin.getline(buf,128); write(s,buffer(buf,strlen(buf)+1), err); if(ec) break; size_t n = s.read_some(buffer(buf,128), err); if (ec) break; std::cout.write(buf, n-1); } } 22
Notes on Previous Code The example client opens a socket to the server machine and loops on reading data from cin, sending that data to the server, wait server reply and prints the reply. If exits if the server does not respond. The example server creates a listening socket and waits for a client to connect. When it gets a connection, it waits for a message from the client and send that exact same message back to the client (echo). If the connection is broken, it closes the connection and creates a new listening socket. 23