ipc 2 Flashcards
What are Sockets?
- Sockets are an extension of pipes, with the advantages that processes don’t need to be related, or even on the same machine
– Method for accomplishing interprocess communication
– Bidirectional communication - A socket is like the end point of a pipe – in fact, the Linux kernel implements pipes as a pair of sockets
- Two (or more) sockets must be connected before they can be used to transfer data
Socket Client-Server Model
- IPC using sockets described as client-server model
– One process is usually called the server
– A server process is usually responsible for satisfying requests made by other processes called clients
– A server usually has a well-known address (e.g., IP address or pathname)
Socket Attributes
Sockets are characterized by three attributes
– Domain
– Type
– Protocol
Socket Protocol
– Determined by socket type and domain
– Default protocol is 0
- For communication between processes, sockets can be implemented in the following domains
– UNIX (e.g., AF_UNIX) - Processes are on the same machine
– INET (e.g., AF_INET) - Each process is on a different machine (i.e., requires a network interface device)
types of sockets
Three main types of sockets:
– SOCK_STREAM (TCP sockets)
* Provides a connection-oriented, sequenced, reliable, and bidirectional network communication service
* E.g., telnet, ssh, HTTP
– SOCK_DGRAM (UDP sockets)
* Provides a connectionless, unreliable, best-effort network communication service
* E.g., streaming audio/video, IP telephony
– SOCK_RAW
* Allows direct access to other layer protocols such as IP, ICMP, or IGMP
UNIX Domain Sockets
include <sys/un.h>
- Socket for communicating with another process on the same machine only
– Provides an optimization since no network overhead - Uses sockaddr_un structure instead of sockaddr_in
struct sockaddr_un
{
sa_family_t sun_family; /* AF_UNIX /
char sun_path[108]; / pathname */
};
Stream Socket
- Sequence of function calls for a client and server to implement a stream socket
Steps in Server Process
- Call socket() with proper arguments to create the socket
- Call bind() to bind the socket to an address (in our case, it is just a pathname) in the UNIX domain
- Call listen() to instruct the socket to listen for incoming connections from client programs
- Call accept() to accept a connection from a client
- Handle the connection and loop back to accept()
- Close the connection
Steps in Client Process
- Call socket() to get a UNIX domain socket to communicate through
- Set up a struct sockaddr_un with the remote address (where the server is listening) and call connect() with that as an argument
- Assuming no errors, you are connected to the remote side
– Use send() and recv() to communicate
Creating the Socket
include <sys/types.h>
#include <sys/socket.h>
int socket(int domain, int type, int protocol);
- Creates an endpoint for communication (i.e., a socket) and returns a file descriptor
- Common domains (or address family)
– AF_UNIX Unix domain sockets
– AF_INET IPv4 Internet sockets
– AF_INET6 IPv6 Internet sockets - Type
– SOCK_STREAM, SOCK_DGRAM, SOCK_RAW - Protocol
– Set to 0 (chosen by OS) except for RAW sockets
Bind to a Name (Server Side)
include <sys/types.h>
#include <sys/socket.h>
int bind(int sockfd, const struct sockaddr *serveraddr, socklen_t addrlen);
- Binds a name to the socket (i.e., reserves a port)
- sockfd is the socket file descriptor returned by socket
- serveraddr is the IP address and port of the machine (address usually set to INADDR_ANY – chooses a local address)
- addrlen is the size (in bytes) of the structure
- Returns 0 on success or –1 if an error occurs
- When socket is bound, new special socket-type file (type “s”) corresponding to sun_path is created
- This file is not automatically deleted, so need to unlink it
– If bind finds the file already exists, it will fail
int listen (int sockfd, int backlog) (Server Side)
include <sys/types.h>
#include <sys/socket.h>
int listen(int sockfd, int backlog);
- Listens for connections on a socket
– After calling listen(), a socket is ready to accept connections - Prepares a queue in the kernel where partially completed connections wait to be accepted
- Many client requests may arrive
– Server cannot handle them all at the same time
– Server could reject the requests or let them wait
– backlog is the maximum number of partially completed connections that the kernel should queue - What if too many clients arrive?
– Some requests don’t get through … makes no promises
– And the client(s) can always try again!
Establish Connection (Server Side)
include <sys/types.h>
#include <sys/socket.h>
int accept(int sockfd, struct sockaddr* cliaddr, socklen_t * addrlen);
- Accepts a connection on the socket and returns a new file descriptor that refers to the connection with the client that will be used for reads and writes on the connection
– Blocks waiting for a connection (from the queue) - sockfd is the listening socket
- cliaddr is the address of the client
Establish Connection (Client Side)
include <sys/types.h>
#include <sys/socket.h>
int connect(int sockfd, const struct sockaddr* servaddr, socklen_t * addrlen);
- Initiates a connection on the socket, where the kernel will select a source IP address and dynamic port
- Returns 0 on success or –1 on failure
Sending Data
include <sys/types.h>
#include <sys/socket.h>
ssize_t send(int sockfd, const void *buf, size_t len, int flags);
- Alternative to write that sends a message on the socket
- sockfd is socket descriptor for open and connected socket
- buf is a buffer of information to send
- len is the size of the buffer in bytes
- flags
– Bitwise OR of zero or more flags (e.g., MSG_EOR, MSG_OOB, etc.) - Calls are blocking (i.e., returns only after data is sent)
Receiving Data
include <sys/types.h>
#include <sys/socket.h>
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
- Alternative to read that receives a message on the socket
- sockfd is socket descriptor for open and connected socket
- buf is initially empty to store the data
- len is the size of the buffer in bytes
- flags
- Bitwise OR of zero or more flags (e.g., MSG_EOR, MSG_OOB, etc.)
- Calls are blocking (returns only after data is received)
Close and Shutdown
include <unistd.h></unistd.h>
int close(sockfd);
* Closes the file descriptor when done
* Will not deallocate the socket until we close the last descriptor that references it (we may have several)
int shutdown(int sockfd, int how);
* Forces a full or partial closure of a socket
* sockfd is a socket descriptor
* how can be SHUT_RD, SHUT_WR, or SHUT_RDWR
Socket Pipe
- What if you wanted a pipe(), but you wanted to use a single pipe to send and receive data from both sides?
– Since most pipes are unidirectional (with exceptions in SYSTEM V), you cannot do it!
– Unix System V is one of the first commercial versions of the Unix OS - UNIX domain sockets can handle bi-directional data
– But, you would have to set up all that code with listen() and connect() with everything just to pass data both ways - However, you can use socketpair() that returns a pair of already connected sockets
– No extra work needed and you can immediately use the socket descriptors for interprocess communication (only available in UNIX domain socket)
socketpair() Function
include <sys/socket.h>
int socketpair(int family, int type, int protocol, int sockfd[2]);
- Creates two unnamed sockets that are already connected
(Unnamed: A stream socket that has not been bound to a pathname using bind(2) has no name) - They are full-duplex (i.e., data can go in each direction)
- Also called stream pipes if type is SOCK_STREAM
- Returns 0 on success, –1 on error
- Family must be AF_LOCAL or AF_UNIX
- Type is SOCK_DGRAM or SOCK_STREAM
- Protocol must be 0
Layers of the IP Protocol Suite
application layer -> ftp
transport layer -> TCP, UDP
network layer -> IP
link layer -> ethernet
Internet Sockets
- Sockets provide a mechanism to communicate between computers across a network
- Internet Sockets
– AF_INET – the addresses are IPv4 addresses
– AF_INET6 – the addresses are IPv6 addresses
What is the Internet?
Physical layer
Actual electrons on a wire
Datalink layer
Frames, MAC Addresses
Network layer
Router to router, Creates network IP addresses, Variable-length packets
Transport layer
Persistent communication channels, TCP, UDP, ports
Session layer
Open, close, manage sessions; AppleTalk, SCP
Presentation layer
String encoding,encryption /decryption
Object serialization, files, compression
Application layer
HTTP POST and GET requests
Byte Ordering of Integers
- Different CPU architectures have different byte ordering. Byte ordering is an attribute of the processor, not the operating system running on it.
- In computing, endianness is the order or sequence of bytes of a word of digital data in computer memory.
- Endianness is expressed as big-endian or little-endian
- Endianness may also be used to describe the order in which the bits are transmitted over a communication channel, e.g., big-endian in a communications channel transmits the most significant bits first
- Little-Endian
– Stores the least significant byte (LSB) in the smallest address - Big-Endian
– Stores the most significant byte (MSB) in the smallest address - In order to connect to a remote computer and use a socket, we need to use its address
– In fact, Linux is little-endian, but TCP/IP uses big-endian byte ordering
Byte Ordering
- A byte (of 8 bits) has a limited range of 256 values. When a value is beyond this range, it has to be stored in multiple bytes.
- A number such as 753 in hexadecimal format is 0x02F1. It requires at least two bytes of storage. The order in which these two bytes are stored in memory can be different. Byte 0x02 can be stored in lower memory address followed by 0xF1; or vice versa.
- Programs must conform to the byte ordering as supported by the processor. If not, 0x02F1 might be wrongly interpreted as 0xF102, which is the number 61698 in decimal system. Byte ordering is also important when data is transferred across a
network or between systems using different ordering.
Byte Ordering Problem
What would happen if two computers with different integer byte ordering communicate?
– Nothing… if they do not exchange integers!
– But… if they exchange integers, they would get the wrong order of bytes, and therefore, the wrong value!