Docsity

Understanding Sockets and their Role in Network Communication, Study notes of Electrical and Electronics Engineering

Toggle sidebar
bg1
Sockets!
What exactly are sockets?!
•!an endpoint of a connection!
•!similar to UNIX file I/O API (provides a file descriptor)!
•!associated with each end-point (end-host) of a connection!
•!identified by the IP address and port number of both the sender and receiver!
Berkeley sockets is the most popular network API!
•!runs on Linux, FreeBSD, OS X, Windows!
•!fed/fed off the popularity of TCP/IP!
•!can build higher-level interfaces on top of sockets!
•!e.g., Remote Procedure Call (RPC)!
Based on C, single threaded model!
•!does not require multiple threads!
Useful sample code available at!
•!http://www.kohala.com/start/unpv12e.html!
Process File Table and Socket Descriptor!
Stevens TCP/IP Illustrated v. 2 p. 446!
sd!
Types of Sockets!
Different types of sockets implement different service models!
•!Stream v.s. datagram!
Stream socket (aka TCP)!
•!connection-oriented!
•!reliable, in order delivery!
•!at-most-once delivery, no duplicates!
•!used by e.g., ssh, http!
Datagram socket (aka UDP)!
•!connectionless (just data-transfer)!
•!ā€œbest-effortā€ delivery, possibly lower variance in delay!
•!used by e.g., IP telephony, streaming audio, streaming video, Internet gaming, etc.!
Simplified E-mail Delivery!
You want to send email to [email protected]!
At your end, your mailer!
•!translates cs.usc.edu to its IP address (128.125.1.45)!
•!decides to use TCP as the transport protocol (Why?)!
•!creates a socket!
•!connects to 128.125.1.45 at the well-known SMTP
port # (25)!
•!parcels out your email into packets !
•!sends the packets out!
On the Internet, your packets got:!
•!transmitted!
•!routed!
•!buffered!
•!forwarded, or!
•!dropped!
At the receiver, smtpd!
•!must make a ā€œreceiverā€ ahead of time:!
•!creates a socket!
•!decides on TCP!
•!binds the socket to smtp’s well-
known port #!
•!listens on the socket!
•!accepts your smtp connection
requests!
•!recves your email packets!
pf3
pf4
pf5

Partial preview of the text

Download Understanding Sockets and their Role in Network Communication and more Study notes Electrical and Electronics Engineering in PDF only on Docsity!

Sockets!

What exactly are sockets?!

-! an endpoint of a connection! -! similar to UNIX file I/O API (provides a file descriptor)! -! associated with each end-point (end-host) of a connection! -! identified by the IP address and port number of both the sender and receiver!

Berkeley sockets is the most popular network API!

-! runs on Linux, FreeBSD, OS X, Windows! -! fed/fed off the popularity of TCP/IP! -! can build higher-level interfaces on top of sockets! -! e.g., Remote Procedure Call (RPC)!

Based on C, single threaded model!

-! does not require multiple threads!

Useful sample code available at!

-! http://www.kohala.com/start/unpv12e.html!

Process File Table and Socket Descriptor!

Stevens TCP/IP Illustrated v. 2 p. 446! sd!

Types of Sockets!

Different types of sockets implement different service models!

-! Stream v.s. datagram!

Stream socket (aka TCP)!

-! connection-oriented! -! reliable, in order delivery! -! at-most-once delivery, no duplicates! -! used by e.g., ssh, http!

Datagram socket (aka UDP)!

-! connectionless (just data-transfer)! -! ā€œbest-effortā€ delivery, possibly lower variance in delay! -! used by e.g., IP telephony, streaming audio, streaming video, Internet gaming, etc.!

Simplified E-mail Delivery!

You want to send email to [email protected]!

At your end , your mailer!

-! translates cs.usc.edu to its IP address (128.125.1.45)! -! decides to use TCP as the transport protocol (Why?)! -! creates a socket! -! connects to 128.125.1.45 at the well-known SMTP port # (25)! -! parcels out your email into packets! -! sends the packets out!

On the Internet , your packets got:!

-! transmitted! -! routed! -! buffered! -! forwarded, or! -! dropped!

At the receiver , smtpd!

• !must make a ā€œreceiverā€ ahead of time:!

• !creates a socket!

• !decides on TCP!

• !binds the socket to smtp’s well-

known port #!

• !listens on the socket!

• !accepts your smtp connection

requests!

• !recves your email packets!

Stream/TCP Sockets!

socket () bind () listen () accept () recv () close () socket () connect () send () recv () send () time^ close () initialize establish data xfer terminate Client Server

Stream/TCP Socket!

Server:!

!! server process must first be

running!

!! server must have created

socket (door) that

welcomes client’s contact!

Client:!

!! creates client-local TCP

socket!

!! specifies IP address, port

number of server process!

!! When client contacts

server: client TCP

establishes connection to

server TCP!

!! When contacted by client, server TCP creates new socket for server process to communicate with client

-! allows server to talk with multiple clients -! source port numbers used to distinguish clients

Initialize (Client)!

int sd; if ((sd = socket (AF_INET, SOCK_STREAM , IPPROTO_TCP)) < 0) { perror("socket"); printf("Failed to create socket\n"); abort(); }

socket()creates a socket data structure and attaches it to the process’s file

descriptor table!

Handling errors that occur rarely usually consumes most of systems code!

Establish (Client)!

struct sockaddr_in sin; struct hostent *host = gethostbyname(argv[1]); unsigned int server_addr = *(unsigned long *) host->h_addr_list[0]; unsigned short server_port = atoi(argv[2]); memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = server_addr; sin.sin_port = htons( server_port ); if ( connect (sd, (struct sockaddr *) &sin, sizeof (sin)) < 0) { perror("connect"); printf("Cannot connect to server\n"); abort(); } connect() initiates connection (for TCP)!

Establish (Server accept)!

int addr_len = sizeof(addr); int td; td = accept( sd , (struct sockaddr *) &addr, &addr_len); if ( td < 0) { perror("error accepting connection"); abort(); }

•! waits for incoming client connection!

•! returns a connected socket (different from the listened to socket)!

API design question: why not merge listen() and accept()?!

Socket

Connection

Queues!

Stevens TCP/IP Illustrated v. 2 pp. 441, 461! sd! sd! td! td!

Receiving Data Stream (Server)!

int receive_packets(char *buffer, int buffer_len, int *bytes_read) { int left = buffer_len - *bytes_read; received = recv( td , buffer + *bytes_read, left, 0);

.... return 0; }

!! returns the number of bytes actually received!

!! 0 if connection is closed, -1 on error!

!! if non-blocking: -1 if no data, with errno set to EWOULDBLOCK!

!! must loop to ensure all data is received!

!! Why doesn’t recv return all of the data at once?!

!! How do you know you have received everything sent?!

Connection close (Client and Server)!

• !close() marks socket unusable!

• !actual tear down depends on TCP"

bind: Address already in use

• !socket option SO_LINGER can be used to specify whether close()

should return immediately or abort connection or wait for termination!

• !The APIs getsockopt() and setsockopt() are used to query and set

socket options (see UNP Ch. 7)!

• !Other useful options:!

-! SO_RCVBUF and SO_SNDBUF used to set buffer sizes! -! SO_KEEPALIVE tells server to ping client periodically!

How to Handle Multiple I/O Streams?!

Where do we get incoming data?!

-! stdin (typically keyboard/mouse input)! -! sockets!

Asynchronous arrival, program doesn’t know when data will arrive!

Alternatives:!

multithreading: each thread handles one I/O stream (482)! I/O multiplexing: a single thread handles multiple I/O streams" Flavors:! a.! blocking I/O (default):!

-! put process to sleep until I/O is ready! -! blocking for: device availability and I/O completion! -! by polling or use of select() b.! non-blocking I/O:! -! only checks for device availability! -! by polling or signal driven (not covered)! c.! asynchronous I/O:! -! process is notified when I/O is completed (not covered)!

Non-Blocking I/O: Polling!

int opts = fcntl(sock, F_GETFL); if (opts < 0) { perror("fcntl(F_GETFL)"); abort(); } if (fcntl(sock, F_SETFL, opts | O_NONBLOCK) < 0) { perror("fcntl(F_SETFL)"); abort(); } while (1) { if (receive_packets(buffer, buffer_len, &bytes_read) != 0) { break; } if (read_user(user_buffer, user_buffer_len, &user_bytes_read) != 0) { break; } } get data from socket get user input get current socket option settings set non-blocking I/O socket option

Blocking I/O: select()

select(maxfd, readset, writeset, exceptset, timeout)

-! waits on multiple file descriptors/sockets and timeout! -! application does not consume CPU cycles while waiting! -! maxfd is the maximum file descriptor number + 1! -! if you have only one descriptor, number 5, maxfd is 6! -! descriptor sets provided as bit mask! -! use FD_ZERO, FD_SET, FD_ISSET, and FD_CLR " to work with the descriptor sets! -! returns as soon as one of the specified sockets are ready "

to be read or written, or they have an error, or timeout exceeded!

-! returns # of ready sockets, -1 on error, 0 if timed out and no device is ready (what for?)!

Blocking I/O: select()

fd_set read_set; struct timeval time_out; while (1) { FD_ZERO(read_set); FD_SET(stdin, read_set); /* stdin is typically 0 / FD_SET(sd, read_set); time_out.tv_usec = 100000; time_out.tv_sec = 0; err = select(MAX(stdin, sd) + 1, &read_set, NULL, NULL, &time_out); if (err < 0) { perror ("select"); abort (); } if (err > 0) { if (FD_ISSET(sd, read_set)) if (receive_packets(buffer, buffer_len, &bytes_read) != 0) break; if (FD_ISSET(stdin, read_set)) if (read_user(user_buffer, user_buffer_len, &user_bytes_read) != 0) break; } else {... / timed out */ } } set up parameters for select() run select() interpret result

Naming and Addressing!

Example DNS name in ASCII string: www.eecs.umich.edu!

Its IP address in dotted-decimal (dd) ASCII string: 141.212.113.110!

Its IP address in 32-bit binary representation:!

Why do we need names instead of using the addresses directly?!

Why do we need addresses in addition to names?!

Name and Address Manipulation!

Syscalls to map name to/from address:!

  • dns to binary: gethostbyname()!
  • binary to dns: gethostbyaddress()!

and to change representation:!

  • dd to binary: inet_aton()!
  • binary to dd: inet_ntoa()!

dns to dd: gethostbyname() plus inet_ntoa()"

gethostbyname() and gethostbyaddr() both return "

struct hostent that contains both binary & dd (See Fig. 11.2 of UNP)!

Other useful syscalls:!

  • !gethostname(): returns DNS name of current host!
  • !getsockname(): returns IP address bound to socket (in binary)" Used when address and/or port is not specified (INADDR_ANY), " to find out the actual address and/or port used!
  • !getpeername(): returns IP address of peer (in binary)! Flat vs. Hierarchical Space!

Example of flat name space:!

-! file system that doesn’t support folders/sub-directories!

Examples of hierarchical name space:!

-! Duncan McLeod, William Wallace!

Examples of hierarchical address space:!

-! 5 Wilberforce Rd., Cambridge, Cambridgeshire, England, UK! -! Japan, Tokyo-to, Minato-ku, Shirokanedai 4-chome 6-41! -! +1 734 763 1583!

Why form hierarchy?!

  • !John Doe!
  • !John Smith!
  • !John Keynes!
  • !John Woo!

Advantage of hierarchical space: allows for decentralized management!