Sockets provide an interface between applications and the network. An application creates a socket which can be either connection-oriented or connectionless. The socket type determines the communication style. Once configured, the application can send and receive data through the socket to communicate over the network. There are two main socket types - SOCK_STREAM for reliable connections and SOCK_DGRAM for unreliable datagrams. Socket addresses contain the IP address and port number to identify the endpoint of communication.
In this document
Powered by AI
Defines a socket as an interface between application and network. It can be TCP or UDP, identified by IP address and port.
Explains SOCK_STREAM and SOCK_DGRAM types, detailing characteristics such as delivery reliability and connection orientation.
Describes socket creation using C, including parameters like domain, type, and protocol. Lists protocol families (IPv4, IPv6 etc.).
Details different socket types (including sequenced and raw sockets) and their structures, emphasizing socket address handling.
Discusses the importance of byte ordering (network vs. host), and functions for converting values in network programming.
Highlights functions for network address conversion and their implementation in socket programming, including inet_ntop and sockaddr structures.
Defines readn, writen, and readline functions for socket data transmission, emphasizing how they handle byte transfers.Illustrates the Daytime server/client application, detailing the files needed and how to compile/run both server and client.
Introduces essential socket functions such as socket(), bind(), listen() and their role in establishing connections.
Explains the connect and bind functions, including their parameters, error returns, and significance in TCP connections.
Describes the usage of the listen function, its parameters, queued connections, and handling incoming requests.
Discusses how to implement a concurrent server model using fork and exec functions to handle multiple client requests.
Clarifies how to obtain local and remote addresses of sockets using getsockname and getpeername functions.
Details the implementation of a TCP echo server/client application, demonstrating how to exchange messages.
What is asocket?
ď‚—An interface between application and network
ď‚—The application creates a socket
ď‚—The socket type dictates the style of communication
ď‚— reliable vs. best effort
ď‚— connection-oriented vs. connectionless
ď‚—Once configured the application can
ď‚—pass data to the socket for network transmission
ď‚—receive data from the socket (transmitted through the
network by some other host)
3.
What is Socket?
ď‚—Endpoint of any connection
ď‚—Two Types :
ď‚—TCP
ď‚—UDP
ď‚—Identified by Two values
ď‚—An IP Address
ď‚—A Port Number
4.
Two essential typesof
sockets
ď‚— SOCK_STREAM ď‚— SOCK_DGRAM
ď‚— reliable delivery ď‚— unreliable delivery
ď‚— in-order guaranteed ď‚— no order guarantees
 connection-oriented  no notion of “connection” – app
ď‚— bidirectional indicates dest. for each packet
ď‚— can send or receive
App
App D1
3 2 1
socket Dest.
3 2 1
socket D2
D3
4
5.
SERVER SIDE socket()
Socket Functions
Well
known bind()
port
CLIENT SIDE listen()
socket() accept()
Connection establishment
connect() Blocks until
(TCP three-way handshake) connection
from client
write()
Data (request) read()
Process request
Data (reply) write()
read()
End-of-file notification
close() read()
Running an App close()
6.
Socket Creation inC: socket
ď‚—int s = socket(domain, type, protocol);
ď‚—s: socket descriptor, an integer (like a file-handle)
ď‚—domain: integer, communication domain
 e.g., AF_INET (IPv4 protocol) – typically used
ď‚—type: communication type
ď‚— SOCK_STREAM: reliable, 2-way, connection-based service
ď‚— SOCK_DGRAM: unreliable, connectionless,
7.
Socket Creation inC: socket
ď‚—protocol: specifies protocol (see file /etc/protocols for a
list of options) –
usually set to 0 to select the system’s default for the
given combination of family and type.
ď‚—NOTE: socket call does not specify where data will be
coming from, nor where it will be going to – it just creates
the interface!
Type of socket
Type Description
SOCK_STREAM STREAM socket
SOCK_DGRAM Datagram socket
SOCK_SEQPACKET Sequenced packet socket
SOCK_RAW Raw socket
10.
Protocol of socket
protocol description
IPPROTO_TCP TCP transport protocol
IPPROTO_UDP UDP transport
protocol
IPPROTO_SCTP SCTP transport
protocol
11.
Addresses, Ports andSockets
ď‚—Like apartments and mailboxes
ď‚— You are the application
ď‚— Your apartment building address is the address
ď‚— Your mailbox is the port
ď‚— The post-office is the network
ď‚— The socket is the key that gives you access to the right mailbox
(one difference: assume outgoing mail is placed by you in your
mailbox)
Socket Address Structure
ď‚—Lengthfield simplifies the handling of variable-length
socket address structures.
ď‚—Used with routing socket.
ď‚—In_addr_t datatype must be an unsigned integer type
of at least 32 bits.
14.
Datatype
Datatype Description Header
Int8_t Signed 8-bit integer <sys/types.h>
Uint8_t unsigned 8-bit integer <sys/types.h>
Int16_t Signed 16-bit integer <sys/types.h>
Uint16_t unsigned 16-bit integer <sys/types.h>
Int32_t Signed 32-bit integer <sys/types.h>
Uint32_t unsigned 32-bit integer <sys/types.h>
Sa_family_t Add. Family of socket add <sys/socket.h>
struct
Socklen_t Length of socket add struct <sys/socket.h>
In_addr_t IPV4 address, uint32_t <netinet/in.h>
15.
Generic Socket Addressstructure
ď‚—A Socket address structure must be passed by
reference
ď‚—socket function that takes one of these pointers as an
argument must deal with socket address structures
from any of the supported protocol families.
ď‚—How to declare the type of pointer
ď‚—Soln : void *
ď‚—Define Generic socket address structure
ď‚—<sys/socket.h>
16.
Generic Socket Addressstructure
ď‚—Struct sockaddr
{
uint8_t sa_len;
sa_family_t sa_family;
char sa_data[14];/* protocol specific address*/
};
From an application programmer's point of view, the
only use of these generic socket address structures is
to cast pointers to protocol-specific structures.
New Generic SocketAddress structure
ď‚—Struct sockaddr
{
uint8_t sa_len;
sa_family_t sa_family;
/* implementation dependent elements to
provide
1. alignment
2. enough storage to hold any type of socket
address that the system supports */
};
19.
sockaddr_storage different fromstruct sockaddr
in two ways:
ď‚—If any socket address structures that the system
supports have alignment requirements, the
sockaddr_storage provides the strictest alignment
requirement.
ď‚—The sockaddr_storage is large enough to contain any
socket address structure that the system supports.
Value-result Arguments
ď‚—Accept ,recvfrom , getpeername pass socket address
structure from kernel to the process.
ď‚—Size changes from an int to pointer to an integer is
because the size is both a value when the function is
called and Result when function returns.
ď‚—connect (sockfd, (SA *) &serv, sizeof(serv));
ď‚—getpeername(unixfd, (SA *) &cli, &len);
23.
Address and portbyte-ordering
ď‚—Address and port are stored as integers
ď‚— u_short sin_port; (16 bit)
ď‚— in_addr sin_addr; (32 bit)
Problem:
different machines / OS’s use different word orderings
• little-endian: lower bytes first
• big-endian: higher bytes first
these machines may communicate with one another over the
network
Big-Endian
Little-Endian
machine
machine
G !!
!12.40.119.128
ON40 12
128.119.40.12
128 R
128 119 40 12 W 119
23
24.
Solution: Network Byte-Ordering
ď‚—Defs:
ď‚—Host Byte-Ordering: the byte ordering used by a
host (big or little)
ď‚—Network Byte-Ordering: the byte ordering used by
the network – always big-endian
ď‚—Any words sent through the network should be
converted to Network Byte-Order prior to
transmission (and back to Host Byte-Order once
received)
25.
Byte Ordering Functions
ď‚—program
ď‚—Twotypes of Byte Ordering
ď‚—Little-endian Byte Ordering
Address A+1 Address A
MSB LSB
ď‚—Big-endian Byte Ordering
Address A Address A+1
MSB LSB
26.
determine host byteorder
int main(int argc, char **argv)
{
union
{ short s;
char c[sizeof(short)];
} un;
un.s = 0x0102;
printf("%s: ", CPU_VENDOR_OS);
if (sizeof(short) == 2)
{ if (un.c[0] == 1 && un.c[1] == 2)
printf("big-endiann");
else if (un.c[0] == 2 && un.c[1] == 1)
printf("little-endiann");
else
printf("unknownn");
}
else
printf("sizeof(short) = %dn", sizeof(short));
exit(0);
27.
Byte Ordering Functions
ď‚—<netinet/in.h>
ď‚—uint16_thtons(uint16_t host16val); -- convert 16-bit
value from host to network order, used for the port
number.
ď‚—uint32_t htonl(uint32_t host32val); -- convert 32-bit
value from host to network order, used for the Ipv4
address.
ď‚—uint16_t ntohs(uint16_t network16val); -- convert 16-bit
value from network to host order.
ď‚—uint32_t ntohl(uint32_t network32val); -- convert 32-bit
value from network to host order.
28.
Byte Ordering Functions
ď‚—#include<strings.h>
ď‚—Voidbzero(void *dest, size_t nbytes);
-- SETS THE SPECIFIED NO. OF BYTES TO O IN THE
DESTINATION.
ď‚—Void bcopy(const void *src, void *dest, size_t nbytes);
-- copies nbytes of src to dest.
ď‚—int bcmp(const void *ptrl, const void *ptr2, size_t
nbytes);
-- compare nbytes of the two strings, Returns 0 if
they match, >0 if ptr1 >ptr2, < 0 if ptr1 < ptr2.
29.
ď‚—void *memset(void *dest,int c, size_t nbytes);
---- writes value c in the destination
----bytes of dest. Returns dest.
ď‚—void *memcpy(void *dest, const void *src, size_t
nbytes);
---- copies nbytes of src to dest. Returns dest.
ď‚—int memcmp(const void *ptrl, const void *ptr2, size_t
nbutes);
---- compare nbytes of the two strings, Returns 0 if
they match, >0 if ptr1 >ptr2, < 0 if ptr1 < ptr2.
30.
Inet_aton, inet_addr, inet_ntoa
Aninternet address is written as: “192. 43. 234.1”,
saved as a character string. The functions require
their number as a 32-bit binary value.
ď‚—<arpa/inet.h>
ď‚—int inet_aton(const char *strptr, struct in_addr *
addrptr);
-- returns 1, 0 on error.
Converts from a dotted-decimal string to a network
address.
31.
Inet_aton, inet_addr, inet_ntoa
ď‚—In_addr_tinet_addr(const char *strptr);
-- Converts from a dotted-decimal string to 32-bit
interger as return value.
--INADDR_NONE IF ERRORs
ď‚—char *inet_ntoa (struct in_addr addrptr);
-- Returns a pointer to a dotted-decimal string, given
a valid network address.
32.
Inet_pton functions
#include<arpa/inet.h>
ď‚—Convert strptr ( which is in presentation form ) to
numeric form and store it into addrptr.
ď‚—int inet_pton(int family, const char *strptr, void
*addrptr);
-- returns 1 if OK, 0 if invalid input format, -1 on error.
33.
inet_ntop functions
ď‚—Const char*inet_ntop (int family, const void *addrptr,
char *strptr, size_t len);
-- returns pointer to result if OK, NULL on error.
--len argument is the size of the destination, to
prevent the function from overflowing the caller’s
buffer
Two functions supports both IPv4 and IPv6 protocol
35.
Sock_ntop function
ď‚—A basicproblem with inet_ntop is that it requires the
caller to pass a pointer to a binary address.
ď‚—This address is normally contained in a socket address
structure,
ď‚—Requiring the caller to know the format of the
structure and the address family.
36.
Sock_ntop function
ď‚—struct sockaddr_inaddr;
inet_ntop(AF_INET, &addr.sin_addr, str, sizeof(str));
ď‚—For IPV6 struct sockaddr_in6 addr6;
inet_ntop(AF_INET6, &addr6.sin6_addr, str,
sizeof(str));
ď‚—sock_ntop that takes a pointer to a socket address
structure, looks inside the structure, and calls the
appropriate function to return the presentation format of
the address.
37.
Sock_ntop function
ď‚—char *sock_ntop(conststruct sockaddr *sockaddr,
socklen_t addrlen);
Returns: non-null pointer if OK, NULL on error
ď‚—sockaddr points to a socket address structure whose
length is addrlen.
ď‚— The function uses its own static buffer to hold the
result and a pointer to this buffer is the return value.
38.
sock_ntop and relatedfunctions.
ď‚—int sock_bind_wild(int sockfd, int family);
ď‚—Returns: 0 if OK, -1 on error
ď‚—sock_bind_wild binds the wildcard address and an
ephemeral port to a socket.
39.
sock_ntop and relatedfunctions.
ď‚—sock_cmp_addr compares the address portion of
two socket address structures
ď‚—int sock_cmp_addr(const struct sockaddr
*sockaddr1,const struct sockaddr *sockaddr2,
socklen_t addrlen);
ď‚—Returns: 0 if addresses are of the same family
and ports are equal, else nonzero
40.
sock_ntop and relatedfunctions
ď‚—int sock_cmp_port(const struct sockaddr
*sockaddr1,const struct sockaddr *sockaddr2,
socklen_t addrlen);
ď‚—Returns: 0 if addresses are of the same family and ports
are equal, else nonzero
ď‚—sock_cmp_port compares the port number of two
socket address structures.
41.
sock_ntop and relatedfunctions
ď‚— sock_get_port returns just the port number
ď‚—int sock_get_port(const struct sockaddr *sockaddr,
socklen_t addrlen);
ď‚—Returns: non-negative port number for IPv4 or IPv6
address, else -1
42.
sock_ntop and relatedfunctions
ď‚—char *sock_ntop_host(const struct sockaddr
*sockaddr, socklen_t addrlen);
ď‚—Returns: non-null pointer if OK, NULL on error
ď‚—sock_ntop_host converts just the host portion of a
socket address structure to presentation format (not
the port number).
43.
sock_ntop and relatedfunctions
ď‚—void sock_set_addr(const struct sockaddr *sockaddr,
socklen_t addrlen, void *ptr);
ď‚—sock_set_addr sets just the address portion of a
socket address structure to the value pointed to by ptr
44.
sock_ntop and relatedfunctions
ď‚—void sock_set_port(const struct sockaddr *sockaddr,
socklen_t addrlen, int port)
ď‚—sock_set_port sets just the port number of a socket
address structure
ď‚—void sock_set_wild(struct sockaddr *sockaddr,
socklen_t addrlen);
ď‚—sock_set_wild sets the address portion of a socket
address structure to the wildcard
45.
readn, writen, andreadline Functions
ď‚—A read or write on a stream socket might input or
output fewer bytes than requested.
ď‚—Buffer limits might be reached for the socket in the
kernel.
#include "unp.h“
ď‚—ssize_t readn(int filedes, void *buff, size_t nbytes);
ď‚—ssize_t writen(int filedes, const void *buff, size_t
nbytes);
ď‚—ssize_t readline(int filedes, void *buff, size_t maxlen);
All return: number of bytes read or written, –1 on
error
46.
readn function: Readn bytes from a descriptor.
ď‚—#include "unp.h"
ssize_t readn(int fd, void *vptr, size_t n)
{ size_t nleft; ssize_t nread; char *ptr; ptr = vptr; nleft =
n;
while (nleft > 0)
{ if ( (nread = read(fd, ptr, nleft)) < 0)
{ if (errno == EINTR)
nread = 0; /* and call read() again */
else
return (-1);
}
else if (nread == 0)
break; /* EOF */
nleft -= nread;
ptr += nread;
}
readline function: Reada text line from a
descriptor, one byte at a time.
ď‚— ssize_t readline(int fd, void *vptr, size_t maxlen)
{ ssize_t n, rc; char c, *ptr; ptr = vptr;
for (n = 1; n < maxlen; n++)
{ again : if ( (rc = read(fd, &c, 1)) == 1)
{ *ptr++ = c;
if (c == 'n')
break; /* newline is stored, like fgets() */
} else if (rc == 0)
{ *ptr = 0;
return (n - 1); /* EOF, n - 1 bytes were read */
} else
{ if (errno == EINTR)
goto again;
return (-1); /* error, errno set by read() */
}
}
*ptr = 0; /* null terminate like fgets() */
return (n); }
49.
Example – DaytimeServer/Client
Application protocol
Daytime client Daytime server
Socket API Socket API
TCP protocol
TCP TCP
IP protocol
IP IP
MAC-level protocol
MAC driver MAC driver
Actual data flow
MAC = media
Network access control
50.
Files to becreated
ď‚—Client STRING Server
Client Server
ď‚—Client source file - client.c
ď‚—Server source file - server.c
ď‚—Header file - header.h
51.
Running an Application
ď‚—Compileand run server file ( you can run it as a
background process too)
e.g. $cc server.c
$./a.out 2345 &
ď‚—Compile and Run client file
e.g. $cc client.c
$./a.out 172.16.2.2 2345
Thu March 05 15:50:00 2009
Back
52.
abstract
ď‚—Socket function
ď‚—connect function
ď‚—bind function
ď‚—listen function
ď‚—accept function
ď‚—fork and exec function
ď‚—concurrent server
ď‚—close function
ď‚—getsockname and getpeername function
53.
SERVER SIDE socket()
Socket Functions
Well
known bind()
port
CLIENT SIDE listen()
socket() accept()
Connection establishment
connect() Blocks until
(TCP three-way handshake) connection
from client
write()
Data (request) read()
Process request
Data (reply) write()
read()
End-of-file notification
close() read()
Running an App close()
54.
#include <sys/socket.h>
int socket(intfamily, int type, int protocol);
returns:nonnegative descriptor if OK, -1 on error
==>Normaly the protocol argument to the socket function is set to 0
exept for raw socket.
56.
connect Function
#include<sys/socket.h>
ď‚—int connect(int sockfd, const struct sockaddr
*servaddr, socklen_t addrlen);
ď‚—Returns : 0 if successful connect, -1 otherwise
ď‚—sockfd: integer, socket to be used in connection
ď‚— struct sockaddr: address of passive participant
ď‚— integer, sizeof(struct)
(If connect fails, the SYN_SENT socket is no longer
useable.)
57.
Connection Setup (SOCK_STREAM)
ď‚—Aconnection occurs between two kinds of
participants
ď‚—passive: waits for an active participant to request
connection
ď‚—active: initiates connection request to passive side
ď‚—Once connection is established, passive and
active participants are “similar”
ď‚—both can send & receive data
ď‚—either can terminate the connection
58.
Connect function
ď‚—Return error
ď‚—ETIMEOUT : no response from server
ď‚—RST : server process is not running
EHOSTUNREACH : client’s SYN unreachable
from some
intermediate router.
59.
Error Return byConnect
ď‚—If the client TCP receives no response to its SYN
segment, ETIMEDOUT is returned.
If the server’s response to the client’s SYN is a
reset (RST), this indicates that no process is
waiting for connections on the server host at the
port specified.
ď‚—Hard error
ď‚— ECONNREFUSED is returned to the client as soon as the RST is
received.
60.
Error Return byConnect
ď‚—Three conditions that generate an RST are:
ď‚—When a SYN arrives for a port that has no listening server
ď‚—When TCP wants to abort an existing connection
ď‚—When TCP receives a segment for a connection that does
not exist.
61.
Error Return byConnect
ď‚—ICMP destination unreachable received in response to
client TCP’s SYN (maybe due to transient routing
problem), resend SYN timeout after 75 sec, returns
EHOSTUNREACH or ENETUNREACH
62.
connect Function: Three-WayHandshake
• No bind before connect :The kernel chooses the source IP, if
necessary, and an ephemeral port (for the client).
Hard error: RST received in response to client TCP’s SYN (server not
running) returns ECONNREFUSED
Soft error:
1. no response to client TCP’s SYN, resend SYN, timeout after 75 sec (in
4.4BSD), returns ETIMEOUT
2. ICMP destination unreachable received in response to client TCP’s SYN
(maybe due to transient routing problem), retx SYN, timeout after 75 sec,
returns EHOSTUNREACH)
63.
The bind function
ď‚—Assigns a local protocol address to a socket.
ď‚—int status = bind(int sockid, const struct sockaddr
&myaddr, socklen_t addrlen);
ď‚—status: error status, = -1 if bind failed, 0 if OK.
ď‚—sockid: integer, socket descriptor
ď‚—myaddr: struct sockaddr, the (IP) address and port of
the machine (address usually set to INADDR_ANY –
chooses a local address)
ď‚—addrlen: the size (in bytes) of the addrport structure
64.
bind Function
ď‚—Usually serversbind themselves to their well-known
ports.
ď‚—RPC servers let kernel choose ephemeral ports which
are then registered with the RPC port mapper.
ď‚—Normally, TCP client does not bind an IP address to
its socket.
ď‚—If a TCP server does not bind an IP address to its
socket, the kernel uses the destination IP address of
the client’s SYN as the server’s source IP address
65.
bind Function
Table summarizesthe values to which we
set sin_addr and sin_port depending on the
desired result.
Process specifies
IP address port Result
Wildcard 0 kernel chooses IP addr and port
wildcard nonzero kernel chooses IP addr, process specifies port
local IP addr 0 kernel chooses port, process specifies IP addr
local IP addr nonzero process specifies IP addr and port
66.
bind Function
ď‚—Wildcard addressis specified by the constant
INADDR_ANY whose value is normally 0.
ď‚—To obtain value of the ephemeral port assigned by the
kernel, we must call getsockname to return the
protocol address.
67.
listen function
#include <sys/socket.h>
intlisten(int sockfd, int backlog);
Returns:0 if OK, -1 on error
==>This function is called only by a TCP server
ď‚— The listen function converts an unconnected socket into a passive
socket, indicating that the kernel should accept incoming connection
requests directed to this socket.
ď‚— backlog =>specify the maximum number of connections that the
kernel should queue for this socket.
ď‚— If the queues are full when client SYN arrives, TCP server ignore the
SYN, it does not send RST.
68.
listen function
â—Ź
Anincomplete connection queue, which contains an entry
for each SYN that has arrived from a client for which the
server is awaiting completion of the TCP three-way
handshake
â—Ź
A completed connection queue, which contains an entry for
each client with whom the TCP three-way handshake has
completed
70.
Backlog argument tothe listen function has historically specified the maximum
value for the sum of both queues
71.
listen Function
ď‚—Backlog argumentto listen function has specified the
maximum value for the sum of both queues
ď‚—Berkeley derived : multipied by 1.5
ď‚—Do not specify backlog of 0
ď‚—What value should the application specify?
ď‚—Allow Command line or an environment variable to
override default.
72.
Listen that allowsan environment var to specify backlog
ď‚—Void Listen(int fd, int backlog)
{ char *ptr;
if ((ptr=getenv(“LISTENQ”))!=NULL)
backlog=atoi(ptr);
if (listen(fd,backlog)<0)
printf(“listen error”);
}
73.
listen Function
ď‚—If thequeues are full when a client SYN arrives, TCP
ignores the arriving SYN : it does not send an RST.
ď‚—Data that arrives after the three way handshake
completes, but before the server call accept, should be
queued by the server TCP, up to the size of the
connected socket’s receive buffer.
74.
accept function
#include <sys/socket.h>
intaccept(int sockfd, struct sockaddr *cliaddr,
socklen_t *addrlen);
Returns:nonnegative descriptor if OK, -1 on error
=> return the next completed connection from the
front of the completed connection queue.
If queue is empty, the process is put to sleep.
75.
Return three values:
1.integer return code
2. protocol address of the client process
3. size of this address :
This integer value contains the actual number of bytes
stored by the kernel in the socket address structure.
If we are not interested in having the protocol address of the
client returned, we set both cliaddr and addrlen to null
pointers.
76.
fork and execfunction
#include <unistd.h>
pid_t fork(void);
Returns: 0 in child, process ID of child in parent, -1 on error
#include <unistd.h>
int execl(const char *pathname, const char *arg(), …/*(char *) 0*/);
int execv(const char *pathname, char *const argv[]);
int execle(const char *pathname, const char *arg());
int execve(const char *pathname, char *const argv[], char *const
envp[]);
int execlp(const char *filename, const char *arg());
int execvp(const char *filename, char *const argv[]);
All six return: -1 on error, no return on success
77.
ď‚—A process makesa copy of itself so that one copy can
handle one operation while the other copy does
another task.
ď‚—A process wants to execute another program. Since
the only way to create a new process is by calling fork,
the process first calls fork to make a copy of itself, and
then one of the copies (typically the child process)
calls exec to replace itself with the new program.
78.
ď‚—The differences inthe six exec functions are:
(a) whether the program file to execute is specified by a
filename or a pathname;
(b) whether the arguments to the new program are
listed one by one or referenced through an array of
pointers; and
(c) Whether the environment of the calling process is
passed to the new program or whether a new
environment is specified.
80.
Concurrent server
pid_t pid
intlistenfd, connfd;
listenfd = Socket(...);
//fill in sockaddr_in{} with server’s well-known port
Bind(listenfd, LISTENQ);
for(;;){
connfd = Accept(listenfd, ...);
if( (pid = Fork()) == 0)
{
Close(listenfd); /* child closes listening socket */
doit(connfd); //process the request
Close(); //done with this client
exit(0); //child terminate
}
Close(connfd); // parent close connected socket
82.
close
ď‚—When finished usinga socket, the socket should be
closed:
ď‚—status = close(s);
ď‚—status: 0 if successful, -1 if error
ď‚—s: the file descriptor (socket being closed)
ď‚—Closing a socket
ď‚—closes a connection (for SOCK_STREAM)
ď‚—frees up the port used by the socket
84.
Return the addressfamily of socket
ď‚—#include "unp.h"
ď‚— int sockfd_to_family(int sockfd)
ď‚—{
ď‚— struct sockaddr_storage ss;
ď‚— socklen_t len;
ď‚— len = sizeof(ss);
ď‚— if (getsockname(sockfd, (SA *) &ss, &len) < 0)
ď‚— return (-1);
ď‚— return (ss.ss_family);
ď‚—}
85.
getsockname and getpeername
function
#include<sys/socket.h>
intgetsockname(int sockfd, struct sockaddr *localaddr,
socklen_t *addrlen);
int getpeername(int sockfd, struct sockaddr *peeraddr,
socklen_t *addrlen);
both return : 0 if OK, -1 on error
=>getsockname : return local address associated with a socket
getpeername : foreign protocol address associated with a socket
86.
getsockname and getpeername
Thisfunction takes the following three input arguments:
1. The sockets to query for the socket address.
2. The pointer to the receiving buffer (argument name).
3. Pointer to the maximum length variable. This variable
provides the maximum length in bytes that can be
received in the buffer (argument namelen).
87.
Reasons:
ď‚—TCP client thatdoes not call bind, getsockname
returns the local protocol address
ď‚—After calling bind with a port no. of 0,
getsockname returns the local port number
ď‚—It can be called to obtain the address family of a
socket.
ď‚—Server binds to wildcard IP address,getsockname
used to obtain the local protocol address
ď‚—Only way to obtain the identity of client is to call
getpeername
88.
Value-result Arguments
ď‚—when asocket address structure is passed to any
socket function, it is always passed by reference.
ď‚—That is, a pointer to the structure is passed.
ď‚— The length of the structure is also passed as an
argument. But the way in which the length is passed
depends on which direction the structure is being
passed: from the process to the kernel, or vice versa.
ď‚—Bind, connect, and sendto pass socket address
structure from the process to kernel
90.
Files to becreated
ď‚—Client STRING Server
Client Server
ď‚—Client source file - client.c
ď‚—Server source file - server.c
ď‚—Header file - header.h
91.
TCP Echo Client/Server
ď‚—The client reads a line of text from its standard
input and writes the line to the server.
ď‚— The server reads the line from its network input and
echoes the line back to the client.
ď‚— The client reads the echoed line and prints it on its
standard output.
92.
TCP Echo Server:main Function
ď‚—Create socket, bind server's well-known port
ď‚—Wait for client connection to complete
ď‚—Concurrent server
ď‚—H:echo_server.c
ď‚—Header file : unp.h
93.
TCP echo client.
ď‚—Createsocket, fill in Internet socket address
structure
ď‚—Connect to server
ď‚—G:echo_client.c.txt
94.
TCP Echo Client:str_cli
Function
ď‚—Read a line, write to server
ď‚—Read echoed line from server, write to standard
output
ď‚—Return to main