0% found this document useful (0 votes)
5 views16 pages

Sockets C

The document discusses the communication between processes in computer networking, focusing on the use of sockets as the API for interaction with the transport layer. It outlines the requirements for internet transport services, comparing TCP and UDP protocols, and provides examples of socket programming for both TCP and UDP. The document also includes code snippets for a TCP client and server, demonstrating how they interact to send and receive data.

Uploaded by

Jake C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

Sockets C

The document discusses the communication between processes in computer networking, focusing on the use of sockets as the API for interaction with the transport layer. It outlines the requirements for internet transport services, comparing TCP and UDP protocols, and provides examples of socket programming for both TCP and UDP. The document also includes code snippets for a TCP client and server, demonstrating how they interact to send and receive data.

Uploaded by

Jake C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Computer Networking and Applications

How processes communicate


• Sockets provide the applica.on programmers’ interface (API)
between a process and the transport layer (sys/socket.h,
java.net).
• User applica.on code runs on end-systems - not network core
• The applica.on programmer needs to specify
– which transport protocol to use
– what host to send messages to (e.g. IP address or hostname)
– what process on the des.na.on host to send messages to (port number)
application application
socket process
controlled by
process app developer

transport transport
network network controlled
link by OS
link Internet
physical ©Kurose & Ross 2013
physical
Computer Networking and Applications
Internet Transport Services
• What services do applica.ons need?
– Reliable data transfer, Minimum throughput guarantees,
Bounded delays, Security
• What do the Internet protocols provide?
– Reliable data transfer with transmission control protocol TCP
– Minimal overhead, available bandwidth/delays, no delivery
guarantee with user datagram protocol UDP
– emerging protocols for providing .ming and bandwidth
guarantees
• Current choices in Internet are TCP or UDP. How does a
network applica.on designer decide?
Computer Networking and Applications

Transport service requirements: common apps

application data loss throughput time sensitive

file transfer no loss elastic no


e-mail no loss elastic no
Web documents no loss elastic no
real-time audio/video loss-tolerant audio: 5kbps-1Mbps yes, 100’s msec
video:10kbps-5Mbps
stored audio/video loss-tolerant same as above yes, few secs
interactive games loss-tolerant few kbps up yes, 100’s msec
text messaging no loss elastic yes and no
Computer Networking and Applications
Socket Programming with TCP

• Recall that TCP provides a reliable byte stream. All of our data will
be going to the same host and port (ie to the same process).
• Assume we want to get a web page. We want to talk to
www.foo.com on port 80. If we stay connected to the socket on
port 80, how will www.foo.com service other requests?
• port 80 is used to establish a connec.on on a second server socket.
connect
client TCP
socket port 80
port nnn accept socket
bytes
new
bytes socket
port 80
Computer Networking and Applications
Socket programming with TCP

Application Example:
1. Client reads a character (data) from its keyboard
and sends the data to the server.
2. The server receives the data and converts character
to uppercase.
3. The server sends the modified data to the client.
4. The client receives the modified data and displays
the character on its screen.

©Kurose & Ross 2001


Computer Networking and Applications
Client/server socket interaction: TCP
server (running on hostid) client
create socket,
port=x, for incoming
request:
listen_socket = socket()
bind( )

wait for incoming create socket,


connection request
TCP connect to hostid, port=x
listen() connection setup client_socket = socket()
connection_socket = accept() connect( )

send request using


read request from client_socket
connection_socket

write reply to
connection_socket read reply from
client_socket
Close
connection_socket Close
client_socket

Application Layer 2-6


Computer Networking and Applications

C TCP Client
#include <sys/types.h> // socket, recv, send, close
#include <sys/socket.h>
#include <netdb.h> // getaddrinfo
Libraries we #include <unistd.h> // close
will use #include <string.h> // memset
#include <stdio.h> // fgets, fputs, puts
#include <stdbool.h> // true false “localhost” works if the
server is running on the
int main(int argc, char *argv[]) { same computer as the
client. Effectively “this
Set these to computer”
char * SERVER_NAME = "localhost";
the
char * SERVER_PORT = "6789"; The port must be the
hostname
and port of port the server is
the SERVER listening on.

You need to set these


for *your* application.

Application Layer 2-7


Computer Networking and Applications
C TCP Client

/* Set socket address structures */


struct addrinfo hints; // hints for the type of socket wanted
struct addrinfo * server_addr; // holder for the address information

/* clear memory of the structures */


memset(&hints,0,sizeof(hints));
The address information is
memset(&server_addr,0,sizeof(server_addr)); now stored in server_addr.
We will use this information
to create and connect the
/* set hints on type of connec.on */ socket
hints.ai_family = AF_INET; /* set address family to IPv4 */
hints.ai_socktype = SOCK_STREAM; /* use TCP stream */

getaddrinfo(SERVER_NAME, SERVER_PORT, &hints, &server_addr);


Computer Networking and Applications
C TCP Client

/* Create socket */
int client_socket = socket(server_addr->ai_family, server_addr->ai_socktype, 0);

/* connect socket */
if (connect(client_socket, server_addr->ai_addr, server_addr->ai_addrlen))
perror("connect failed: ");
Note we can use perror( ) to
print out the reason for
char character; failure. This should be done
for all function calls that
while(true) {
might fail.
puts("Input lowercase letter: ");
character = getchar(); Loop forever getting a
send(client_socket,&character,sizeof(char),0); character from the user,
sending it to the server
on the connected
socket…
Computer Networking and Applications
C TCP Client

puts("Server returned: ");


recv(client_socket, &character, sizeof(char),0);
… still in the loop. Read
putchar(character); what character the server
sends back on the
connected socket and print
getchar(); // read the newline character
it.
putchar('\n');

}
We won’t ever reach this code since we
close(client_socket);
have an infinite loop above. But if we
were to finish we should close the
freeaddrinfo(server_addr); connected socket so the server knows we
are finished and free dynamic memory.
}
Both will happen automatically (by the
operating system) if we kill the client
process.
Computer Networking and Applications
C TCP Server

#include <sys/types.h> // socket, recv, send, close bind


#include <sys/socket.h>
Libraries we will use.
#include <netdb.h> // getaddrinfo
#include <unistd.h> // close Note similarities and
#include <string.h> // memset differences from client
#include <ctype.h> // toupper
#include <stdlib.h> // NULL This is the port the
server will listen on and
int main(int argc, char *argv[]) the client will connect
{ to. If it doesn’t match,
struct addrinfo hints; // fill this in with the type of address wanted the client will not reach
struct addrinfo * server_addr; // structure to hold server's address the server application.
int listen_socket, connection_socket; QLEN is the number of
char * DEFAULT_PORT = "6789"; simultaneous requests.
int QLEN = 1; We will only connect to
one client at a time.

Application Layer 2-11


Computer Networking and Applications
C TCP Server

/* Set up server address structure: serv_addr */ Address set up is similar to


/* This sets the port and and IP address that we will bind to */ the client address set up
/* the socket we just created */

memset(&hints, 0, sizeof(hints));
memset(&server_addr,0,sizeof(server_addr)); /* clear sockaddr structure */ But notice this
difference. This hint
hints.ai_family = AF_INET; tells getaddrinfo to fill in
hints.ai_socktype = SOCK_STREAM; my (the servers)
address for me.
hints.ai_flags = AI_PASSIVE; // fill in my IP address

getaddrinfo(NULL, DEFAULT_PORT, &hints, &server_addr);


I don’t have to give the
server name like I did
in the client.

Application Layer 2-12


Computer Networking and Applications
C TCP Server

/* Create a socket */
listen_socket = socket(server_addr->ai_family, server_addr->ai_socktype, 0);

/* Bind the socket to the address information set in serv_addr */


bind(listen_socket, server_addr->ai_addr, server_addr->ai_addrlen);
Different here! The
/* Start listening for connections */ client just connected.
listen(listen_socket, QLEN); The server must bind,
listen and accept.
/* Accept and handle requests */
connection_socket = accept(listen_socket, NULL, NULL);
We have two sockets
now.
connection_socket and
listen_socket. Which
will we talk to the client
on?
Application Layer 2-13
Computer Networking and Applications
C TCP Server

/* Receive the characters */


char character;
char capital_character; Receive returns the
number of characters
while(recv(connection_socket, &character, sizeof(char),0)) { read and will receive 0
/* send capitalised character back */ when the client closes
capital_character = (char) toupper((int)character); the socket.
send(connection_socket, &capital_character, sizeof(char),0);
}

/* finished, close the socket */ Send it back to the


close(connection_socket); client
close (listen_socket);
} How would this differ if we
wanted to keep running the
server and accept another
client connection? Application Layer 2-14
Computer Networking and Applications
Socket programming with UDP

UDP: no “connec.on” between client


and server
• no handshaking
application viewpoint
• sender explicitly a_aches IP address
and port of des.na.on UDP provides unreliable transfer
• server must extract IP address, port of groups of bytes (“datagrams”)
of sender from received datagram between client and server

UDP: transmi_ed data may be received


out of order, or lost

©Kurose & Ross 2001


Computer Networking and Applications
Client/server socket interaction: UDP

server (running on serverIP) client


create socket:
create socket, port= x: clientSocket =
serverSocket =
socket(AF_INET,SOCK_DGRAM) socket(AF_INET,SOCK_DGRAM)
bind()
Create datagram with server IP and
port=x; send datagram via
read datagram recvfrom() clientSocket
serverSocket

write reply sendto()


serverSocket read datagram from
specifying clientSocket
client address,
port number close
clientSocket

Application 2-16

You might also like