CS438 02.Sockets
-
Upload
adwait-prasada-nayak -
Category
Documents
-
view
224 -
download
0
Transcript of CS438 02.Sockets
-
8/6/2019 CS438 02.Sockets
1/90
Introduction to Unix Network
Programming
Reference: Stevens Unix
Network Programming
-
8/6/2019 CS438 02.Sockets
2/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 2
How do we Communicate? Send a mail from Alice to Bob
Alice in Champaign, Bob in Hollywood
Example:
US Postal Service
Bob
Champaign, Illinois
Hollywood, California
Alice
-
8/6/2019 CS438 02.Sockets
3/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 3
What does Alice do?
Bobs address (to a mailbox)
Bobs name in case people share mailbox
Postage have to pay!
Alices own name and address in case Bob wants to return amessage
Bob
100 Santa Monica Blvd.
Hollywood, CA 90028
Alice
200 Cornfield Rd.
Champaign, IL 61820
-
8/6/2019 CS438 02.Sockets
4/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 4
What does Bob do?
Install a mailbox
Receive the mail
Get rid of envelope
Read the message
Bob
100 Santa Monica Blvd.
Hollywood, CA 90028
Alice
200 Cornfield Rd.
Champaign, IL 61820
-
8/6/2019 CS438 02.Sockets
5/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 5
What about sending a TCP/IP
packet?
Very similar to Alice-mailing-to-Bob
Different terminologies veryconfusing
We have to remember
Different technologies
Suppose to be better (faster, more
reliable, cheaper, )
-
8/6/2019 CS438 02.Sockets
6/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 6
Two simplest networking
programs Alice
the sending process
Alices address:128.174.246.177 (IP addr)
Alices name: 12345 (port #)
Bob the receiving process
Bobs address:216.52.167.132 (IP addr)
Bobs name: 23456 (port #)
int main () {
int sockfd;
struct sockaddr_in bob_addr, alice_addr;
bzero(&bob_addr, sizeof(bob_addr));
bob_addr.sin_family = AF_INET;bob_addr.sin_addr.s_addr = 0xD834A784;
bob_addr.sin_port = 23456;
// do the same for alice_addr
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
sendto(sockfd, hi, strlen(hi), 0,
&bob_addr, sizeof(bob_addr));
}
int main () {
int sockfd, n;
struct sockaddr_in bob_addr, alice_addr;
char mesg[100];
bzero(&bob_addr, sizeof(bob_addr));bob_addr.sin_family = AF_INET;
bob_addr.sin_addr.s_addr = 0xD834A784;bob_addr.sin_port = 23456;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
bind(sockfd, &bob_addr, sizeof(bob_addr));
n= recvfrom(sockfd, mesg, 100, 0,
&alice_addr, sizeof(alice_addr));
}
-
8/6/2019 CS438 02.Sockets
7/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 7
What are the problems?
Message may be lost
Network is congested
Receiver is congested
Message may be duplicated, corrupted
Multiple messages: re-ordered
Concurrent connections
-
8/6/2019 CS438 02.Sockets
8/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 8
Direction and Principles
Physical
Transport
Data Link
Network
-
8/6/2019 CS438 02.Sockets
9/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 8
Direction and Principles
Physical
Transport
Data Link
Network
Programming
learn to use Internet forcommunication (with focus on
implementation of networking
concepts)
-
8/6/2019 CS438 02.Sockets
10/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 8
Direction and Principles
Physical
Transport
Data Link
Network
Programming
learn to use Internet forcommunication (with focus on
implementation of networking
concepts)
Principles and
Concepts
learn to build network from ground
up
-
8/6/2019 CS438 02.Sockets
11/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 9
Sockets
process
TCP with
buffers,
variables
socket
host or
server
process
TCP with
buffers,
variables
socket
host or
server
Internet
controlled by
app developer
process sends/receivesmessages to/from itssocket
socket analogous tomailbox
sending process relieson transportinfrastructure whichbrings message tosocket at receivingprocess
-
8/6/2019 CS438 02.Sockets
12/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 10
Network Programming with
Sockets
-
8/6/2019 CS438 02.Sockets
13/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 10
Network Programming with
Sockets
Reading: Stevens 2nd ed., Ch. 1-6 or 1st ed., Ch. 1-3, 6
-
8/6/2019 CS438 02.Sockets
14/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 10
Network Programming with
Sockets
Reading: Stevens 2nd ed., Ch. 1-6 or 1st ed., Ch. 1-3, 6
Sockets API: A transport layer service interface
Introduced in 1981 by BSD 4.1
Implemented as library and/or system calls
Similar interfaces to TCP and UDP
Can also serve as interface to IP (for super-user);known as raw sockets
-
8/6/2019 CS438 02.Sockets
15/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 11
Outline
Client-Sever Model
TCP/UDP Overview
Addresses and Data
Sockets API
Example
-
8/6/2019 CS438 02.Sockets
16/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 12
Client-Server Model Asymmetric Communication
Client sends requests
Server sends replies
Server/Daemon Well-known name (e.g., IP address +
port)
Waits for contact
Processes requests, sends replies
Client
Initiates contact Waits for response
Client
Server
Client
Client
Client
-
8/6/2019 CS438 02.Sockets
17/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 13
Socket Communication
Client process Server process
Client
socket
3-way
handshakingListening
socket
Connection
socket
-
8/6/2019 CS438 02.Sockets
18/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 14
Client-Server Communication
Model Service Model
Concurrent: Server processes multiple clients requests
simultaneously
Sequential: Server processes only one clients requests at a time
Hybrid: Server maintains multiple connections, but processes
responses sequentially
Client and server categories are not disjoint A server can be a client of another server
A server can be a client of its own client
-
8/6/2019 CS438 02.Sockets
19/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 15
TCP Connections
Transmission Control Protocol (TCP)
Service
OSI Transport Layer Service Model
Reliable byte stream (interpreted by application)
16-bit port space allows multiple connections on a
single host
Connection-oriented
Set up connection before communicating
Tear down connection when done
-
8/6/2019 CS438 02.Sockets
20/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 16
TCP Service Reliable Data Transfer
Guarantees delivery of all data
Exactly once if no catastrophic failures
Sequenced Data Transfer Guarantees in-order delivery of data
If A sends M1 followed by M2 to B, B never receives M2before M1
Regulated Data Flow Monitors network and adjusts transmission appropriately
Prevents senders from wasting bandwidth
Reduces global congestion problems
Data Transmission Full-Duplex byte stream
-
8/6/2019 CS438 02.Sockets
21/90
-
8/6/2019 CS438 02.Sockets
22/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 18
UDP Services
Unit of Transfer Datagram (variable length packet)
Unreliable No guaranteed delivery
Drops packets silently
Unordered
No guarantee of maintained order of delivery Unlimited Transmission
No flow control
-
8/6/2019 CS438 02.Sockets
23/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 19
Addresses and Data
Internet domain names Human readable
Variable length Ex: sal.cs.uiuc.edu
IP addresses Easily handled by routers/computers
Fixed length Somewhat geographical
Ex: 128.174.252.217
-
8/6/2019 CS438 02.Sockets
24/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 20
Byte Ordering
Big Endian vs. Little Endian Little Endian (Intel, DEC):
Least significant byte of word is stored in the lowestmemory address
Big Endian (Sun, SGI, HP): Most significant byte of word is stored in the lowest
memory address
Network Byte Order = Big Endian Allows both sides to communicate
Must be used for some data (i.e. IP Addresses)
Good form for all binary data
-
8/6/2019 CS438 02.Sockets
25/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 21
Byte Ordering Functions 16- and 32-bit conversion functions (for platform
independence)
Examples:
int m, n;short int s,t;
m = ntohl (n) net-to-host long (32-bit) translations = ntohs (t) net-to-host short (16-bit) translation
n = htonl (m) host-to-net long (32-bit) translationt = htons (s) host-to-net short (16-bit) translation
-
8/6/2019 CS438 02.Sockets
26/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 22
Socket Address Structure IP address:
struct in_addr {in_addr_t s_addr; /* 32-bit IP address */
};
TCP or UDP address:struct sockaddr_in {
short sin_family; /* e.g., AF_INET */ushort sin_port; /* TCP/UDP port */
struct in_addr; /* IP address */};
all but sin_family in network byte order
-
8/6/2019 CS438 02.Sockets
27/90
-
8/6/2019 CS438 02.Sockets
28/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 24
Structure: hostent The hostentdata structure (from
/usr/include/netdb.h)
canonical domain name and aliases
list of addresses associated with machine
also address type and length informationstruct hostent {
char* h_name; /* official name of host */
char** h_aliases; /* NULL-terminated alias list */
int h_addrtype /* address type (AF_INET) */
int h_length; /* length of addresses (4B) */char** h_addr_list; /* NULL-terminated address list */
#define h_addr h_addr_list[0];/* backward-compatibility */
};
-
8/6/2019 CS438 02.Sockets
29/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 25
Address Access/Conversion
Functionsin_addr_t inet_addr (const char* strptr);
Translate dotted-decimal notation to IP address; returns -1 onfailure, thus cannot handle broadcast value 255.255.255.255
int inet_aton (const char *strptr, structin_addr *inaddr); Translate dotted-decimal notation to IP address; returns 1 on
success, 0 on failure
int gethostname (char* name, size_tnamelen); Read hosts name (use with gethostbyname to find local IP)
-
8/6/2019 CS438 02.Sockets
30/90
-
8/6/2019 CS438 02.Sockets
31/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 27
UDP Connection Example
client server
-
8/6/2019 CS438 02.Sockets
32/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 27
UDP Connection Example
client server
socket
-
8/6/2019 CS438 02.Sockets
33/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 27
UDP Connection Example
client server
socket
bind
-
8/6/2019 CS438 02.Sockets
34/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 27
UDP Connection Exampleclient server
socket
socket
bind
-
8/6/2019 CS438 02.Sockets
35/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 27
UDP Connection Exampleclient server
socket
socket
sendto
bind
-
8/6/2019 CS438 02.Sockets
36/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 27
UDP Connection Exampleclient server
socket
socket
sendto
bind
-
8/6/2019 CS438 02.Sockets
37/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 27
UDP Connection Exampleclient server
socket
socket
sendto
bind
recvfrom
-
8/6/2019 CS438 02.Sockets
38/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 27
UDP Connection Exampleclient server
socket
socket
sendto
bind
recvfrom
sendto
-
8/6/2019 CS438 02.Sockets
39/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 27
UDP Connection Exampleclient server
socket
socket
sendto
bind
recvfrom
sendto
-
8/6/2019 CS438 02.Sockets
40/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 27
UDP Connection Exampleclient server
socket
socket
sendto
bind
recvfrom
sendto
recvfrom
-
8/6/2019 CS438 02.Sockets
41/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 27
UDP Connection Exampleclient server
socket
socket
sendto
bind
recvfrom
sendto
recvfrom
close
-
8/6/2019 CS438 02.Sockets
42/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 28
Functions: sendtoint sendto (int sockfd, char* buf, size_t nbytes,
int flags, struct sockaddr* destaddr, intaddrlen);
Send a datagram to another UDP socket. Returns number of bytes written or -1. Also sets errnoon
failure.
sockfd: socket file descriptor (returned from socket)
buf: data buffer
nbytes: number of bytes to try to read
flags: see man page for details; typically use 0 destaddr: IP address and port number of destination socket
addrlen: length of address structure = sizeof (struct sockaddr_in)
-
8/6/2019 CS438 02.Sockets
43/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 29
Functions: recvfromint recvfrom (int sockfd, char* buf, size_t
nbytes, int flags, struct sockaddr* srcaddr,int* addrlen);
Read a datagram from a UDP socket. Returns number of bytes read (0 is valid) or -1. Also sets errno
on failure. sockfd: socket file descriptor (returned from socket) buf: data buffer nbytes: number of bytes to try to read flags: see man page for details; typically use 0
srcaddr: IP address and port number of sending socket
(returned from call) addrlen: length of address structure = pointer to int set to
sizeof (struct sockaddr_in)
-
8/6/2019 CS438 02.Sockets
44/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 30
Socket FunctionsTCP Client
TCP Server
-
8/6/2019 CS438 02.Sockets
45/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 30
Socket Functions socket()TCP Client
TCP Server
-
8/6/2019 CS438 02.Sockets
46/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 30
Socket Functions socket()
bind()Well-known
port
TCP Client
TCP Server
-
8/6/2019 CS438 02.Sockets
47/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 30
Socket Functions socket()
listen()
bind()Well-known
port
TCP Client
TCP Server
-
8/6/2019 CS438 02.Sockets
48/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 30
Socket Functions socket()
listen()
accept()
bind()Well-known
port
TCP Client
TCP Server
-
8/6/2019 CS438 02.Sockets
49/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 30
Socket Functions socket()
listen()
accept()
bind()Well-known
port
blocks until connection
from client
TCP Client
TCP Server
-
8/6/2019 CS438 02.Sockets
50/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 30
Socket Functions socket()
listen()
accept()
socket()
bind()Well-known
port
blocks until connection
from client
TCP Client
TCP Server
-
8/6/2019 CS438 02.Sockets
51/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 30
Socket Functions socket()
listen()
accept()
socket()
bind()Well-known
port
blocks until connection
from clientconnect()
TCP Client
TCP Server
-
8/6/2019 CS438 02.Sockets
52/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 30
Socket Functions socket()
listen()
accept()
socket()
bind()Well-known
port
blocks until connection
from clientconnect()
TCP three-way handshaking
TCP Client
TCP Server
-
8/6/2019 CS438 02.Sockets
53/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 30
Socket Functions socket()
listen()
accept()
socket()
bind()Well-known
port
blocks until connection
from clientconnect()
TCP three-way handshaking
read()
TCP Client
TCP Server
-
8/6/2019 CS438 02.Sockets
54/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 30
Socket Functions socket()
listen()
accept()
socket()
bind()Well-known
port
blocks until connection
from clientconnect()
write()
TCP three-way handshaking
read()
TCP Client
TCP Server
-
8/6/2019 CS438 02.Sockets
55/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 30
Socket Functions socket()
listen()
accept()
socket()
bind()Well-known
port
blocks until connection
from clientconnect()
write()
TCP three-way handshaking
data (request)read()
TCP Client
TCP Server
-
8/6/2019 CS438 02.Sockets
56/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 30
Socket Functions socket()
listen()
accept()
socket()
bind()Well-known
port
blocks until connection
from clientconnect()
write()
TCP three-way handshaking
data (request)read()
process request
TCP Client
TCP Server
-
8/6/2019 CS438 02.Sockets
57/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 31
Socket Functionssocket()blocks until connection
from clientconnect()
write()
TCP three-way handshaking
data (request)read()
process request
TCP ServerTCP Client
write()
read()
data (reply)
close() read()
close()
-
8/6/2019 CS438 02.Sockets
58/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 32
TCP Connection Exampleclient server
socket
socket
connect
bind
listenaccept
write
read
write
read
close
close
read
-
8/6/2019 CS438 02.Sockets
59/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 33
Socket Creation and Setup Include file
Create a socket int socket (int family, int type, int protocol);
Returns file descriptor or -1.
Bind a socket to a local IP address and port number int bind (int sockfd, struct sockaddr* myaddr, int
addrlen);
Put socket into passive state (wait for connections rather thaninitiate a connection). int listen (int sockfd, int backlog);
Accept connections int accept (int sockfd, struct sockaddr*
cliaddr, int* addrlen);
Returns file descriptor or -1.
-
8/6/2019 CS438 02.Sockets
60/90
-
8/6/2019 CS438 02.Sockets
61/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 35
Function: bindint bind (int sockfd, struct sockaddr*myaddr, int addrlen);
Bind a socket to a local IP address and port
number. Returns 0 on success, -1 and sets errnoon failure. sockfd: socket file descriptor (returned from socket) myaddr: includes IP address and port number
IP address: set by kernel if value passed is INADDR_ANY,else set by caller
port number: set by kernel if value passed is 0, else set bycaller
addrlen: length of address structure = sizeof (struct sockaddr_in)
-
8/6/2019 CS438 02.Sockets
62/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 36
TCP and UDP Ports Allocated and assigned by the Internet Assigned
Numbers Authority see RFC 1700 orftp://ftp.isi.edu/in-notes/iana/assignments/port-numbers
-
8/6/2019 CS438 02.Sockets
63/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 36
TCP and UDP Ports Allocated and assigned by the Internet Assigned
Numbers Authority see RFC 1700 orftp://ftp.isi.edu/in-notes/iana/assignments/port-numbers
private/ephemeral ports49152-65535
registered services/ephemeral ports1024-49151
registered and controlled, also used for identity
verification
super-user only
513-1023
standard services (see /etc/services)
super-user only
1-512
-
8/6/2019 CS438 02.Sockets
64/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 37
Functions: listenint listen (int sockfd, int backlog);
Put socket into passive state (wait for connections
rather than initiate a connection). Returns 0 on success, -1 and sets errnoon failure.
sockfd: socket file descriptor (returned from socket)
backlog: bound on length of unaccepted connection
queue (connection backlog); kernel will cap, thus better to
set high
-
8/6/2019 CS438 02.Sockets
65/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 38
Functions: acceptint accept (int sockfd, struct sockaddr* cliaddr,
int* addrlen);
Accept a new connection. Returns file descriptor or -1. Also sets
errnoon failure.
sockfd: socket file descriptor (returned from socket)
cliaddr: IP address and port number of client (returned fromcall)
addrlen: length of address structure = pointer to int set tosizeof (struct sockaddr_in)
addrlenis a value-result argument: the caller passes the size of the address structure, the kernel
returns the size of the clients address (the number of byteswritten)
-
8/6/2019 CS438 02.Sockets
66/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 39
server#include
#include
#include
#include #include
#include
#include
#include
#define PORT 3490 /* well-known port */#define BACKLOG 10 /* how many pending
connections queue
will hold */
-
8/6/2019 CS438 02.Sockets
67/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 40
servermain()
{
int sockfd, new_fd; /* listen on sock_fd, newconnection on new_fd */
struct sockaddr_in my_addr; /* my address */
struct sockaddr_in their_addr; /* connector addr */
int sin_size;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0))==-1){
perror("socket");exit(1);
}
-
8/6/2019 CS438 02.Sockets
68/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 41
server
bzero(&my_addr, sizeof(struct sockaddr));
/* zero the struct */
my_addr.sin_family = AF_INET; /* host byte order */
my_addr.sin_port = htons(MYPORT); /* short, networkbyte order */
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockfd, (struct sockaddr *)&my_addr,
sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
-
8/6/2019 CS438 02.Sockets
69/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 42
server
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
while(1) { /* main accept() loop */
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr*)
&their_addr,&sin_size)) == -1){
perror("accept");
continue;
}
printf("server: got connection from %s\n",
inet_ntoa(their_addr.sin_addr));
-
8/6/2019 CS438 02.Sockets
70/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 43
Establishing a Connection
Include file
int connect (int sockfd, structsockaddr* servaddr, int addrlen);
Connect to another socket.
-
8/6/2019 CS438 02.Sockets
71/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 44
Functions: connect
int connect (int sockfd, structsockaddr* servaddr, int addrlen);
Connect to another socket. Returns 0 on success, -1 and sets errnoon failure.
sockfd: socket file descriptor (returned from socket)
servaddr: IP address and port number of server
addrlen: length of address structure
= sizeof (struct sockaddr_in)
-
8/6/2019 CS438 02.Sockets
72/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 45
client
if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1) {
perror (socket);
exit (1);
}
their_addr.sin_family = AF_INET; /* interpd by host */
their_addr.sin_port = htons (PORT);
their_addr.sin_addr = *((struct in_addr*)he->h_addr);
bzero (&(their_addr.sin_zero), 8);
/* zero rest of struct */
if (connect (sockfd, (struct sockaddr*)&their_addr,
sizeof (struct sockaddr)) == -1) {
perror (connect);
exit (1);
}
-
8/6/2019 CS438 02.Sockets
73/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 46
Sending and Receiving Data
int write (int sockfd, char* buf, size_tnbytes);
Write data to a stream (TCP) or connected
datagram (UDP) socket. Returns number of bytes written or -1.
int read (int sockfd, char* buf, size_tnbytes);
Read data from a stream (TCP) or connecteddatagram (UDP) socket. Returns number of bytes read or -1.
-
8/6/2019 CS438 02.Sockets
74/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 47
Sending and Receiving Data
int sendto (int sockfd, char* buf,size_t nbytes, int flags, structsockaddr* destaddr, int addrlen);
Send a datagram to another UDP socket. Returns number of bytes written or -1.
int recvfrom (int sockfd, char* buf,size_t nbytes, int flags, struct
sockaddr* srcaddr, int* addrlen); Read a datagram from a UDP socket.
Returns number of bytes read or -1.
-
8/6/2019 CS438 02.Sockets
75/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 48
Functions: write
int write (int sockfd, char* buf, size_tnbytes);
Write data to a stream (TCP) or connected
datagram (UDP) socket. Returns number of bytes written or -1. Also sets errnoonfailure.
sockfd: socket file descriptor (returned from socket) buf: data buffer nbytes: number of bytes to try to write
Some reasons for failure or partial writes: process received interrupt or signal
kernel resources unavailable (e.g., buffers)
-
8/6/2019 CS438 02.Sockets
76/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 49
Functions: read
int read (int sockfd, char* buf, size_tnbytes);
Read data from a stream (TCP) or connected
datagram (UDP) socket. Returns number of bytes read or -1. Also sets errnoon
failure.
Returns 0 if socket closed.
sockfd: socket file descriptor (returned from socket)
buf: data buffer
nbytes: number of bytes to try to read
-
8/6/2019 CS438 02.Sockets
77/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 50
Tearing Down a Connection
int close (int sockfd);
Close a socket.
Returns 0 on success, -1 and sets errnoon failure.
int shutdown (int sockfd, int howto);
Force termination of communication across a socket in
one or both directions.
Returns 0 on success, -1 and sets errnoon failure.
-
8/6/2019 CS438 02.Sockets
78/90
-
8/6/2019 CS438 02.Sockets
79/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 52
Functions: shutdown
int shutdown (int sockfd, int howto);
Force termination of communication across a socket in one orboth directions. Returns 0 on success, -1 and sets errnoon failure.
sockfd: socket file descriptor (returned from socket)
howto: SHUT_RD to stop reading
SHUT_WRto stop writing
SHUT_RDWRto stop both
shutdownoverrides the usual rules regarding duplicatedsockets, in which TCP teardown does not occur until all copieshave closed the socket.
-
8/6/2019 CS438 02.Sockets
80/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 53
Advanced Sockets
Managing Multiple Connections fork/exec: multiple server processes
pthread_create: multi-threaded serverprocess
(no calls): event-based server process
Detecting Data Arrival select andpoll functions
Synchronous vs. AsynchronousConnections
Other Socket Options
-
8/6/2019 CS438 02.Sockets
81/90
-
8/6/2019 CS438 02.Sockets
82/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 55
server
#include
#include
#include
#include #include
#include
#include
#include
#define PORT 3490 /* well-known port */
#define BACKLOG 10 /* how many pending
connections queue
will hold */
-
8/6/2019 CS438 02.Sockets
83/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 56
server
main()
{
int sockfd, new_fd; /* listen on sock_fd, newconnection on new_fd */
struct sockaddr_in my_addr; /* my address */
struct sockaddr_in their_addr; /* connector addr */
int sin_size;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0))==-
1){perror("socket");
exit(1);
}
-
8/6/2019 CS438 02.Sockets
84/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 57
server
my_addr.sin_family = AF_INET; /* host byte order */
my_addr.sin_port = htons(MYPORT); /* short, network
byte order */
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);/* automatically fill with my IP (w/o Beejs bug)*/
bzero(&(my_addr.sin_zero), 8); /* zero the struct*/
if (bind(sockfd, (struct sockaddr *)&my_addr,sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
-
8/6/2019 CS438 02.Sockets
85/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 58
server
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
while(1) { /* main accept() loop */
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr*)
&their_addr,&sin_size)) == -1){
perror("accept");
continue;
}
printf("server: got connection from %s\n",
inet_ntoa(their_addr.sin_addr));
-
8/6/2019 CS438 02.Sockets
86/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 59
server
if (!fork()) { /* this is the child process */
if (send(new_fd,"Hello, world!\n", 14, 0)
== -1)
perror("send");close(new_fd);
exit(0);
}
close(new_fd); /* parent doesn't need this */
/* clean up all child processes */
while(waitpid(-1,NULL,WNOHANG) > 0);}
}
-
8/6/2019 CS438 02.Sockets
87/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 60
client
#include
#include
#include
#include #include
#include
#include
#define PORT 3490 /* well-known port */
#define MAXDATASIZE 100 /* max number of bytes we
can get at once */
-
8/6/2019 CS438 02.Sockets
88/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 61
client
int main (int argc, char* argv[]){
int sockfd, numbytes;
char buf[MAXDATASIZE + 1];
struct hostent* he;
struct sockaddr_in their_addr;/* connectors address information */
if (argc != 2) {
fprintf (stderr, usage: client hostname\n);
exit (1);
}
if ((he = gethostbyname (argv[1])) == NULL) {
/* get the host info */perror (gethostbyname);
exit (1);
}
-
8/6/2019 CS438 02.Sockets
89/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 62
client
if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1) {
perror (socket);
exit (1);
}
their_addr.sin_family = AF_INET; /* interpd by host */
their_addr.sin_port = htons (PORT);
their_addr.sin_addr = *((struct in_addr*)he->h_addr);
bzero (&(their_addr.sin_zero), 8);
/* zero rest of struct */
if (connect (sockfd, (struct sockaddr*)&their_addr,
sizeof (struct sockaddr)) == -1) {perror (connect);
exit (1);
}
-
8/6/2019 CS438 02.Sockets
90/90
8/30/06 UIUC - CS/ECE 438, Fall 2006 63
client
if ((numbytes = recv (sockfd, buf, MAXDATASIZE, 0))
== -1) {
perror (recv);
exit (1);}
buf[numbytes] = \0;
printf (Received: %s, buf);
close (sockfd);
return 0;
}