Intro duction
The So cket Interface cont'd
So ckets are a lo cal and remote OS IPC
abstraction de ned in 4.2 BSD UNIX and
beyond
Originally, so ckets were implemented as a
set of system calls
{ Now part of most major op erating systems, in-
cluding Windows and Win32 systems
{ For eciency, they were tightly-coupled with
the BSD networking architecture in the OS
kernel
So ckets were originally develop ed for TCP/IP
proto cols
Recent versions of so ckets are implemented
{ Later generalized to include other proto col fam-
as a library of functions in user-space
ilies
{ e.g., SVR4 UNIX and Win32
e.g., Novell IPX/SPX, TP4, ATM
User-space implementations improve ex-
So cket routine control communication be-
tween pro cesses and proto cols
ibility and portability at the exp ense of
some p erformance
{ Also provide bu ering between synchronous ap-
plication domain and the asynchronous kernel
domain
2 4
The So cket Interface cont'd
work Programming with Net DISTRIBUTEDAPPLICATION DISTRIBUTEDAPPLICATION DISTRIBUTEDAPPLICATION PROCESS 3592 PROCESS 4183 PROCESS 8729
APPLICATION 1 APPLICATION 2 APPLICATION 3
So ckets
USER
SPACE 255 ECE BSDSOCKET SOCKET SSYSTEMYSTEM V APIAPI TLITLI APIAPI
OS KERNEL KERNEL
C. Schmidt Douglas PROTOCOL SERVICES SPACE
(TCP/IP, OSI, ETC.)
http://www.ece.uci.edu/schmidt/ NETWORK
INTERFACE
University of California, Irvine
An application pro cess using TCP/IP pro-
to cols resides in its own address space
1 3
Communication Domains cont'd
Internet domain or TCP/IP PF INET
Communication Domains cont'd
{ Communicate across network or on same ma-
chine uses \dotted-decimal Internet addresses"
e.g., "128.195.1.1 @ port 21"
UNIX domain PF UNIX
{ Communicate only with a pro cess on the same
{ General-purp ose addressing, but existing ver-
machine
sions don't scale well due to xed-sized ad-
dressing
Uses UNIX lenames for rendezvous between
This is xed in IPv6
client and server pro cesses
{ e.g., TCP, UDP, IP, ftp, rlogin, telnet
{ Really a form of intra-machine IPC, similar to
SVR4 STREAM pip es
STREAM and Supp orts b oth reliable SOCK
Xerox XNS later evolved into Novell IPX
unreliable SOCK DGRAM lo cal IPC
{ SPP, PEX, IDP
Used for lo cal X-windows trac:::
ISO OSI
{ e.g., TP4-TP1, CLNS, CONS
8 6
Communication Domains
Communication domains are a key struc-
turing concept in the BSD networking ar-
chitecture
Communication Domains cont'd
{ e.g., Internet domain and UNIX domain
UNIX cont'd UNIX domain PF
Domains sp ecify:
{ 4.3 BSD and SunOS 4.1.x implement pip es via
\lob otomized" connection-oriented Unix domain
1. The scop e over which two pro cesses may com-
so cket proto col implementations
municate
{ SVR4-based UNIX systems use the STREAMS
{ e.g., lo cal only vs. lo cal/remote
facility
2. How names and addresses are formed and in-
In general, UNIX domain so ckets have b een
terpreted in subsequent so cket calls
subsumed by STREAM-pip es and connld in
SVR4
{ e.g., pathnames vs. IP/p ort numb ers
{ Not surprisingly, Win32 do es not supp ort UNIX
domain so ckets
Most so cket implementations provide sev-
eral domains represented as \proto col fam-
ilies"
{ The socket interface is used for all these pro-
to col family domains
7 5
Stream So cket
Typ e of service
Reliably-delivered Message So cket
{ Reliable i.e., sequenced, non-duplicated, non-
corrupted bi-directional delivery of byte-stream
data
Typ e of service
{ Reliable datagram
Metaphor
{ A \network pip e"
Metaphor
{ Sending a registered letter
e.g.,
INET, SOCK STREAM, 0; int s = so cket PF
e.g.,
/* Note, s is an internal id:::*/
int s = so cket PF NS, SOCK RDM, 0;
Note, we'll use int as the so cket typ e, al-
though Win32 uses SOCKET:: :
12 10
So cket Typ es
Datagram So cket
There are ve Typ es of So ckets
1. Stream So cket
Typ e of service
{ Unreliable, unsequenced datagram
2. Datagram So cket
3. Reliably-delivered Message So cket
Metaphor
4. Sequenced Packet Stream So cket
{ Sending a letter
5. Raw So ckets
e.g.,
SOCK STREAM and SOCK DGRAM are
INET, SOCK DGRAM, 0; int s = so cket PF
the most common typ es of so ckets:::
9 11
So cket Addresses cont'd
Raw So ckets
General Format
Typ e of service
{ Allows user-de ned proto cols that interface with
struct so ckaddr f u short sa family; char sa data[14]; g;
IP
UNIX Domain
{ Requires ro ot access
struct so ckaddr un f
short sun family; char sun path[108];
g;
Metaphor
{ Playing with an erector set:::;-
Internet Domain
addr f unsigned long s addr; g; struct in
struct so ckaddr in f
e.g.,
short sin family; u short sin port;
struct in addr sin addr; char sin zero[8];
INET, SOCK RAW, 0; int s = so cket PF
g;
14 16
So cket Addresses
UNIX supp orts multiple communication do-
Sequenced Packet Stream So cket
mains, proto col families, and address fam-
ilies
Typ e of service
{ The so cket API provides a single address in-
terface for all these families
{ Reliable, bi-directional delivery of record-oriented
data
The typ e of sockaddr structure used with
Metaphor
accept, bind, connect, sendto, and recvfrom
di ers according to the domain UNIX vs.
{ Record-oriented TCP e.g., TP4 and XTP
Internet vs. XNS
e.g.,
The addressing API has a somewhat con-
fusing and error-prone design
int s = so cket PF NS, SOCK SEQPACKET, 0;
{ Motivation was to save space for the \common
case":: :
15 13
So cket Op erations
Connection-oriented So cket
Lo cal context management
Usage
int so cket int domain, int typ e, int proto col;
bind int fd, struct so ckaddr *, int len; int 2: ACTIVE
1: PASSIVE
listen int fd, int backlog; int ROLE
ROLE
close int fd; int socket()
socket()
getp eername int fd, struct so ckaddr *, int *len; int bind() (optional)
bind()
getso ckname int fd, struct so ckaddr *, int *len; int connect() listen() accept()
send()/recv()
Connection establishment and termination send()/recv() close() 3: SERVICE
PROCESSING close()
int connect int fd, struct so ckaddr *, int len;
int accept int fd, struct so ckaddr *, int *len;
int shutdown int fd, int how;
CLIENT
SERVER Option management
NETWORK
int io ctl int fd, int request, char *arg;
int fcntl int fd, int cmd, int arg;
int getso ckopt int, int, int, char *, int *;
int setso ckopt int, int, int, char *, int;
18 20
So cket Op erations
So cket Addresses cont'd
Data transfer
General usage for Internet-domain service:
int read int fd, void *buf, int len;
struct so ckaddr in addr;
int write int fd, void *buf, int len;
int send int fd, void *buf, int len, int ags;
memset &addr, 0, sizeof addr;
int recv int fd, void *buf, int len, int * ags;
addr.sin family = AF INET;
int readv int fd, struct iovec [], int len;
addr.sin port = htons p ort numb er;
int writev int fd, struct iovec [], int len;
addr.sin addr.s addr = htonl INADDR ANY;
int sendto int fd, void *buf, int len, int ags,
struct so ckaddr *, int len;
int recvfrom int fd, void *buf, int len, int ags,
if bind sd, struct so ckaddr * &addr, sizeof addr
struct so ckaddr *, int *len;
== 1
int sendmsg int fd, struct msghdr *msg, int ags;
:::;
int recvmsg int fd, struct msghdr *msg, int ags;
Note the use of a cast
Event demultiplexing
{ In C++, this whole mess can be cleaned-up
via inheritance and dynamic binding!
int select int maxfdp1, fd set *rdfds,
fd set *wrfds, fd set *exfds,
struct timeval *;
17 19
Client and Server Op erations
Client and Server Op erations
cont'd
close
socket
{ Close a so cket
{ Creates and op ens a so cket and returns a de-
{ int close int s;
scriptor
Note, there are subtle semantics related to
{ int s = so cket int domain, int typ e, int pro-
\grace termination:::" of proto cols
to col;
domain ! PF UNIX, PF INET
shutdown
{ Shutdown part or all of full-duplex connection
typ e of service ! SOCK STREAM, SOCK DGRAM
{ int shutdown int s, int how;
proto col ! generally 0, but could be TCP,
how is 0, then further receives will be disal-
VMTP, NETBLT, XTP
lowed
how is 1, then further sends will be disal-
lowed
Note, this call only lls in the rst part of
how is 2, then further sends and receives will
the 5-tuple asso ciation
be disallowed
{ Note, shutdown do es not close the descriptor:::
24 22
Client and Server Op erations
cont'd
Connectionless So cket Usage
bind
Asso ciates a lo cal address e.g., an IP address,
2: ACTIVE {
family, and port numb er to an un-
ROLE 1: PASSIVE address
so cket socket() ROLE named socket()
bind() (optional)
int bind int s, struct so ckaddr *addr, int ad- bind() {
sendto()/ drlen;
recvfrom() sendto()/
addr ! lo cal address e.g., p oints to an In-
recvfrom()
addr or a UNIX domain addr close() 3: SERVICE ternet
PROCESSING close()
addrlen ! length of address
{ Note
CLIENT
SERVER
bind is not necessary for clients which im-
NETWORK
plicitly allo cate transient port numb ers
ANY is a wildcard for The address INADDR
any server host/network interface
Always \zero-out" the address structure be-
fore using it:::
21 23
Typical Server Op erations
accept
Typical Client Op erations
{ Returns a unique descriptor to the next avail-
able completed connection from the connec-
tion queue
connect
{ int accept int s, struct so ckaddr *addr, int
*addrlenptr;
{ Sp ecify foreign/remote destination address e.g.,
IP/p ort numb ers and joins two so ckets for
addr ! address of remote server
I/O:
addrlenptr ! ptr to length of address
{ int connect int s, struct so ckaddr *addr, int
addrlen;
Returns new so cket descriptor sp ecifying the
addr ! address of remote client
full asso ciation
addrlen ! length of address
{ Notes:
1. Server may decide to reject connection only
after rst accepting it!
2. addr and addrlenptr may be 0:::
28 26
Client and Server Op erations
Typical Server Op erations
cont'd
listen
getsockname
{ Set the length of a TCP passive op en queue,
{ Returns address info describing the lo cal so cket
places the so cket into \passive-mo de"
s
This tells kernel to accept connection re-
{ int getso ckname int s, struct so ckaddr *addr,
quests for a listening so cket on b ehalf of a
int *addrlenptr;
client
addr ! address of lo cal binding
{ int listen int s, int backlog;
addrlenptr ! ptr to length of address
backlog ! sp eci es how many connection
requests can be queued
getpeername
{ Note, the kernel will queue a certain numb er
{ Returns the current \name" for the sp eci ed
of incoming connection requests on behalf of
connected p eer so cket
the server
{ int getp eername int s, struct so ckaddr *addr,
Otherwise, p ending requests would be dropp ed
int *addrlenptr;
due to nite limits on OS queue sizes:: :
addr ! address of remote p eer
These limits prevent \denial of service" attacks:::
addrlenptr ! ptr to length of address
27 25
Data Transfer Op erations
Data Transfer Op erations
write
sendto
{ Send a message to a so cket:
{ Send a datagram message from a UDP so cket:
{ int write int s, char *msg, int len;
{ int sendto int s, char *msg, int len, int ags,
msg ! bu er of data to send
struct so ckaddr *addr, int addrlen;
len ! length of bu er
addr ! address of remote server
addrlen ! length of address
send
{ Send a message to a so cket:
recvfrom
{ int send int s, char *msg, int len, int ags;
ags
{ Receive a datagram message from a UCP so cket:
1. MSG OOB ! send out-of-band data on
{ int recvfrom int s, char *buf, int len, int
so ckets that supp ort this op eration
ags, struct so ckaddr *addr, int *addrlenptr;
addr ! address of remote server
Note that neither write nor send are guar-
addrlenptr ! ptr to length of address
anteed to write all the bytes!
30 32
Typical Server Op erations
Data Transfer Op erations
select
read
{ Synchronous event demultiplexer that queries
{ Receive a message from a so cket:
the status of a set of so cket descriptors under
timer control:
{ int read int s, char *buf, int len;
{ int select int maxfdp1, fd set *readfds, fd set
*writefds, fd set *exceptfds, struct timeval *time-
out;
recv
maxfdp1 ! max le descriptor to consider
{ Receive a message from a so cket:
plus 1
{ int recv int s, char *buf, int len, int ags;
readfds ! set of descriptors to check for
reading and incoming connections
ags
writefds ! set of descriptors to check for
1. MSG OOB ! read any out-of-band data
writing and outgoing connections
present on the so cket, rather than the reg-
ular in-band data
exceptfds ! set of descriptors to check for
urgent data
PEEK ! \Peek" at the data present 2. MSG
on the so cket; the data are returned, but
not consumed, so that a subsequent re-
timeout ! length of time to wait for activity
on the descriptors ceive op eration will see the same data
29 31
Option Management cont'd
Internet Domain Stream So ckets
Arguments for setsockopt and getsockopt
Header le
{ level ! proto col level e.g., IP, TCP, so cket,
etc.
include
include
e.g., SOL SOCKET, IPPROTO TCP, IP-
include
IP PROTO
include
include
{ optname ! name of option
include
e.g., SO REUSEADDR, SO ERROR, SO BROADCAST
PORT 7734 de ne SRV
SO SNDBUF, SO RCVBUF
de ne SRV ADDR "128.195.13.4"
de ne STDOUT 1
{ optval ! value of option
de ne STDIN 0
{ optlen ! length of option
int pro cess msg int ifd, int ofd;
34 36
Auxiliary Networking Functions
gethostname
Option Management
{ Returns the primary name of the current host
as an ASCI I string
int gethostname char *name, int namelen;
setsockopt
gethostbyname/gethostbyaddr
{ Sets options on a so cket
struct hostent *gethostbyname char *name;
{ int setso ckopt int s, int level, int optname,
struct hostent *gethostbyaddr char *, int len, int typ e;
void *optval, int optlen;
struct hostent
struct hostent f
getsockopt
name; /* name of host */ char *n
char **h aliases; /* alias list */
int h addrtyp e; /* address typ e */
{ Gets options regarding a so cket
int h length; /* length of addr */
char **h addr list; /* list of addrs */
g;
{ int getso ckopt int s, int level, int optname,
de ne h addr h addr list[0]
void *optval, int *optlenptr;
Note, hostnames/host numb ers are stored
in /etc/hosts
{ Also accessible via DNS:::
33 35
Internet Domain Stream So ckets
Internet Domain Stream So ckets
cont'd
cont'd
Become a passive-mo de \server"
Become an active-mo de \client"
int s server unsigned short port f
int s client u short port, const char *addr f
struct so ckaddr in name;
in name; struct so ckaddr
memset void *, &name, 0, sizeof name;
memset void * &name, 0, sizeof name;
name.sin family = AF INET;
name.sin family = AF INET;
port = htons p ort; name.sin
name.sin port = htons p ort;
name.sin addr.s addr = htonl INADDR ANY;
name.sin addr.s addr = inet addr addr;
int s fd = so cket PF INET, SOCK STREAM, 0;
fd = so cket PF INET, SOCK STREAM, 0; int s
if s fd == 1
if s fd == 1
return 1;
return 1;
fd, &name, sizeof name == 1 else if bind s
else if connect s fd, struct so ckaddr * &name,
return 1;
sizeof name == 1
else if listen s fd, 5 == 1
return 1;
return 1;
return s fd;
return s fd;
g
g
38 40
Internet Domain Stream So ckets
cont'd
Internet Domain Stream So ckets
cont'd
read a message with TCP server
Write a message client
include "header.h"
int main int argc, char *argv[] f
int s fd = s server SRV PORT;
include "header.h"
int main int argc, char *argv[] f
int status = 1;
if s fd == 1
int s fd = s client SRV PORT, SRV ADDR;
p error "s server";
for ;; f
int cli fd = accept s fd, 0, 0;
if s fd == 1
p error "s client";
else if pro cess msg STDIN, s fd == 1
fd == 1 if cli
p error "pro cess msg";
p error "accept";
else
else if pro cess msg cli fd, STDOUT == 1
status = 0;
p error "pro cess msg";
close s fd;
else if close cli fd == 1
return status;
p error "close";
g
g
/* NOTREACHED */
g
37 39
Internet Domain Datagram
// Loop forever performing logging server processing.
for ;; {
So ckets
temp_fds = read_fds; // Structure assignment.
// Wait for client I/O events handle interrupts.
while select maxfdp1, &temp_fds, 0, 0, 0 == -1
Uses UDP to return the current time of
&& errno == EINTR
continue;
day from a sp eci ed list of Internet hosts
// Handle pending logging records first s_fd + 1
// is guaranteed to be lowest client descriptor.
e.g.,
for int fd = s_fd + 1; fd < maxfdp1; fd++
if FD_ISSET fd, &temp_fds {
int n = handle_logging_record fd;
hostdate tango mamb o lambada merengue
// Guaranteed not to block in this case!
tango: timeout at host
if n == -1
perror "logging failed";
mamb o: Tue Aug 20 15:55:59 1996
else if n == 0 {
// Handle client connection shutdown.
FD_CLR fd, &read_fds;
lambada: Tue Aug 20 15:55:59 1996
close fd;
if fd + 1 == maxfdp1 {
merengue: Tue Aug 20 15:56:00 1996
// Skip past unused descriptors.
while !FD_ISSET --fd, &read_fds
continue;
Note the use of select to prevent hang-
maxfdp1 = fd + 1;
}
ing from hosts that are \down" or non-
}
}
existent
42 44
Concurrent Server using Select
// Check for incoming connections.
if FD_ISSET s_fd, &temp_fds {
static struct timeval poll_tv = {0, 0};
Single-threaded concurrent so cket server
// Handle all pending connection requests
// note use of "polling" feature.
int main void
while select s_fd + 1, &temp_fds,
{
0, 0, &poll_tv > 0 {
// Create a server end-point.
int cli_fd = accept s_fd, 0, 0;
int s_fd = s_server PORT_NUM;
fd_set temp_fds;
if cli_fd == -1 perror "accept";
fd_set read_fds;
else {
int maxfdp1 = s_fd + 1;
FD_SET cli_fd, &read_fds;
if cli_fd >= maxfdp1
// Check for constructor failure.
maxfdp1 = cli_fd + 1;
if s_fd == -1
}
perror "server", exit 1;
}
}
FD_ZERO &temp_fds;
}
FD_ZERO &read_fds;
}
FD_SET s_fd, &read_fds;
41 43
Internet Domain Datagram
So ckets cont'd
e.g.,
int do service int sfd, u short port, const char *host f
Advanced So cket Op erations
struct hostent *hp = gethostbyname host;
if hp == 0 return 1;
in sin; struct so ckaddr
family = AF INET; sin.sin
Non-blo cking connections
port = port; sin.sin
memset &sin.sin addr, hp->h addr, hp->h length;
printf "s: ", host; ush stdout;
char buf[BUFSIZ];
Checking for invalid so ckets
if sendto sfd, "", 0, /* Note zero size! */
0, &sin, sizeof sin < 0
Checking for terminated p eers
return 1;
struct timeval tv = f5, 0g;
int len = sizeof sin;
ssize t n = timed recv &tv, sfd, buf, sizeof buf,
&sin, &len;
if n == 1 return n;
printf "*s\n", n, buf ;
return 0;
g
48 46
Internet Domain Datagram
So ckets cont'd
Internet Domain Datagram
Main driver program
So ckets cont'd
de ne SERVICE "daytime"
int do service int, u short, const char *;
Performed \timed receives" for datagrams
int main int argc, char *argv[] f
int timed recv struct timeval *tv, int fd,
int s = so cket PF INET, SOCK DGRAM, 0;
char buf[], int buf size,
if s == 1
struct so ckaddr *sin, int *slen f
p error "argv[0]", exit 1;
fd set read fd;
FD ZERO &read fd;
FD SET fd, &read fd;
struct servent *sp =
getservbyname SERVICE, "udp";
if sp == 0
switch select fd + 1, &read fd, 0, 0, tv f
fprintf stderr, "s/udp: unknown service.\n",
case 0: errno = ETIMEDOUT; /* FALLTHRU */
SERVICE, exit 1;
case 1: return 1;
default:
return recvfrom fd, buf, buf size,
for ++argv ;--argc; ++argv
0, &sin, &slen;
if do service s, sp->s port, *argv == 1
g
p error *argv;
g
close s;
return 0;
g
45 47
Example of Non-Blo cking
Connect
Checking for Invalid So ckets
It is often useful to have the client test if a
This is easier in C++:: :
previously established so cket is still active
b efore trying to write to it
e int nblock_connect int sfd, struct sockaddr *sin, int sinl
{
{ This avoids catching SIGPIPE and such:::
struct timeval timeout = {1, 0};
set_fl sfd, O_NONBLOCK;
if connect sfd, sin, sinlen == -1 {
To do this, rst try to read from the so cket
if errno == EINPROGRESS {
fd_set write_fds;
{ If the client has closed the connection the read
FD_ZERO &write_fds;
should return EOF
FD_SET sfd, &write_fds;
{ if select sfd + 1, 0, write_fds, 0, timeout == 1
if FD_ISSET sfd, &write_fds {
if getpeername sfd, &sin, &sinlen < 0
To keep from hanging in read, rst put the
return -1; /* Connection failed */
so cket descriptor in non-blo cking mo de
}
} else
{ Conversely, use select to nd out whether
/* select timed out, do something else here ... */
read will blo ck:::
} else return -1; /* connect failed unexpectedly */
return sfd; /* Success, we're connected! */
}
52 50
Creating a Non-blo cking So cket
Non-blo cking Connections
Enable I/O descriptor ags
connect may be used in non-blo cking mo de
{ e.g., O NONBLOCK
int set_fl int flags
{
A combination of select, getpeername, and
int val = fcntl fd, F_GETFL, 0;
if val == -1
getsockopt may be used to determine when
return -1;
the connection setup is complete
val |= flags; /* turn on flags */
if fcntl fd, F_SETFL, val == -1
This is useful to avoid long timeouts if
return -1;
return 0;
client may not be accessible
}
49 51
/etc/services
{ List of available network services
{ Accessed via getservbyname, getservbyport
Network Databases and Address
{ e.g.,
Mapping
Service name Port/Protocol Alias
ftp-data 20/tcp
ftp 21/tcp
/etc/hosts supplanted by NIS and DNS
telnet 23/tcp
tftp 69/udp
http 80/tcp
{ List of Internet and lo cal hosts accessible from
talk 517/udp
lo cal machine
uucp 540/tcp uucpd
chforw 701/tcp chforwd
exec 512/tcp execserver
{ Accessed via gethostbyname, gethostbyaddr
login 513/tcp loginserver
{ e.g.,
/etc/proto cols
Subnet 3: Machines on CS subnet
{ information ab out precon gured proto cols
Address Full name Aliases
128.252.165.140 tango.cs.wustl.edu le0-tango
{ e.g.,
128.252.114.18 tango.cs.wustl.edu encip1-tango
Internet ip protocols
128.252.165.145 merengue.cs.wustl.edu le0-merengue
name Number Alias Comment
128.252.165.142 lambada.cs.wustl.edu le0-lambada
ip 0 ip internet protocol, pseudo protocol number
128.252.165.10 cs.wustl.edu cs nfs.cs.wustl.edu nfs
icmp 1 icmp internet control message protocol
ggp 3 ggp gateway-gateway protocol
tcp 6 tcp transmission control protocol
pup 12 pup parc universal packet protocol
udp 17 udp user datagram protocol
54 56
Network Databases and Address
Checking for Terminated Peers
Mapping
A question that often arises is \how do I
get the rst write after the other end has
/etc/networks
terminated to generate SIGPIPE"
{ List of lo cal/Internet networks
The answer is \you can not"
{ Accessed via getnetbyaddr, getnetbyname
{ e.g.,
If you want to know as so on as the pro cess
Net name Net number Alias
at the other end of a connection termi-
uciics-net 128.195
uciics-main 128.195.1 localnet
nates, use select, testing for readability,
uciicslab 128.195.3 ucilabnet uci-labnet
then the read will return 0
uciicsrsh 128.195.4 ucirshnet uci-rshnet
55 53
Unix Domain Stream So ckets
cont'd
Unix Domain Stream So ckets
Become a passive-mo de \server"
UNIX-domain so cket reader header
int s server const char so ck name[] f
include
un name; struct so ckaddr
include
name.sun family = AF UNIX;
include
path, so ck name, sizeof name.sun pat strncpy name.sun
include
include
int s fd = so cket PF UNIX, SOCK STREAM, 0;
include
if s fd == 1
return 1;
de ne SOCK NAME "/tmp/fo o"
else if bind s fd, struct so ckaddr * &name,
de ne STDOUT 1
family + sizeof name.sun
de ne STDIN 0
strlen name.sun path == 1
return 1;
fd, 5 == 1 else if listen s
msg int ifd, int ofd; int pro cess
return 1;
return s fd;
g
58 60
Unix Domain Stream So ckets
Unix Domain Stream So ckets
cont'd
Both of the following Unix domain and In-
ternet domain examples use the following
library routine:
UNIX-domain server
msg int ifd, int ofd f int pro cess
include "header.h"
for char msg[BUFSIZ];; f
void clean up void f unlink SOCK NAME, exit 1; g
ssize t len = read ifd, msg, sizeof msg;
if len > 0 f
if send n ofd, msg, len != len
int main int argc, char *argv[] f
return 1;
signal SIGINT, clean up;
g else return len;
g
return 0;
int s fd = s server SOCK NAME;
g
if s fd == 1
send n is a handy utility routine
p error "s server", clean up ;
for ;; f
ssize t send n int handle, const void *buf, size t len f
int cli fd = accept s fd, 0, 0;
size t bytes written;
if cli fd == 1
ssize t n;
p error "accept";
else if pro cess msg cli fd, STDOUT == 1
for bytes written = 0;
p error "pro cess msg";
bytes written < len;
bytes written += n
else if close cli fd == 1
written, if n = write handle, buf + bytes
p error "close";
len bytes written == 1
g
return 1;
/* NOTREACHED */
written; return bytes
g
g
59 57
Unix Domain Stream So ckets
cont'd
Become an active-mo de \client"
int s client const char so ck name[] f
struct so ckaddr un name;
name.sun family = AF UNIX;
path, so ck name; strcpy name.sun
int s fd = so cket PF UNIX, SOCK STREAM, 0;
if s fd == 1
return 1;
else if connect s fd,
struct so ckaddr * &name,
family sizeof name.sun
+ strlen name.sun path == 1
return 1;
return s fd;
g
62
Unix Domain Stream So ckets
cont'd
UNIX-domain so cket sender
include "header.h"
int main int argc, char *argv[] f
int s fd = s client SOCK NAME;
int status = 1;
if s fd == 1
p error "s client";
else if pro cess msg STDIN, s fd == 1
p error "pro cess msg";
else
status = 0;
close s fd;
return status;
g 61