Chapter 3 - Advanced Sockets Functions
Chapter 3 - Advanced Sockets Functions
Advanced Sockets
Functions
By
En. Mohd Nizam bin Osman
(Senior Lecturer)
Department of Computer Science
Faculty of Computer and Mathematical Science, UiTM Perlis
Course Outline
• select
• getsockname
• getpeername
• getsockopt
• shutdown
• gethostname
• gethostbyaddr
• gethostbyname
• getservbyname
• getservbyport
Sockets Function
SOCKETS FUNCTIONS
Function Description
select Provides event notification of socket events
getsockname Returns the address of the local socket
getpeername Returns the address of the remote socket
getsockopt Returns the value of a socket option for a given socket
setsockopt Manipulates a socket option for a given socket
shutdown Closes a socket with more control
gethostname Retrieves the name of the host on which this stack operates
sethostname Sets the name of the host on which this stack operates
gethostbyaddr Returns the FQDN for a given IP address
gethostbyname Returns the IP address for a given FQDN
getservbyname Returns the port number for a given service string
getservbyport Returns the service string for a given port number
Function
select()
int select (int maxDescPlus1, fd_set *readDescs, fd_Set
*writeDescs, fd_set *exceptionDescs, struct timeval
*timeout);
maxDescsPlus1: integer, hint of the maximum number of descriptors
readDescs: fd_set, checked for immediate input availability
writeDescs: fd_set, checked for the ability to immediately write data
exceptionDescs: fd_set, checked for pending exceptions
timeout: struct timeval, how long it blocks (NULL -> forever)
Client/sever model
struct timeval{
time_ttv_sec;/* seconds */
time_ttv_usec;/* microseconds */
};
Function
getsockname()
int getsockname(int sockfd, struct sockaddr *addr, socklen_t
Client/sever model
*addrlen);
*optVal,
socklen_t
optLen is now optLen);
only an input parameter
It returns -1 if an error occurred
struct servent{
char *s_name; /*official service name*/
char **s_aliases; /*list of alternate names(strings)*/
int s_port; /*service port number*/
char *s_proto; /*protocol to use (“tcp” or “udp”)*/
}
Useful Functions
int atoi (const char *nptr);
Client/sever
Convertsmodel
the initial portion of the string pointed to by nptr to int
int inet_aton(const char *cp, struct in_addr *inp);
Converts the Internet host address cp from IPv4 numbers-and-dots
notation into binary form (in network byte order)
Stores it in the structure that inp ponts to.
It returns nonzero if the address is valid, and 0 if not
char *inet_ntoa(struct in_addr in);
Converts the Internet host address in, given in network byte order,
to a string in IPv4 dotted-decimal notation
typedef uint32_t in_addr_t;
struct in_addr{
int_addr_t s_addr;
};
Iterative Stream Socket Server
Handles one client at a time.
Client/sever model
Additional clients can connect while one is being
served.
Connections are established.
They are able to send requests.
But, the server will respond after it finishes with the first
client.
Works well if each client required a small, bounded
amount of work by the server.
× Otherwise, the client experience long delays.
Iterative Stream Socket Server
Handles one client at a time.
Client/sever model
Additional clients can connect while one is being
served.
Connections are established.
They are able to send requests.
But, the server will respond after it finishes with the first
client.
Works well if each client required a small,
bounded amount of work by the server.
int main ()
{
int listenfd, connfd, n;
socklen_t clilen;
char buf[MAXLINE];
struct sockaddr_in cliaddr, servaddr;
listen(listenfd, LISTENQ);
for ( ; ; ) {
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);
printf("%s\n","Received request...");
}
//close listening socket
close(listenfd);
}
Iterative Server
Example: “Echo Server” using stream socket
//Client
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
int main()
{
int sockfd;
struct sockaddr_in servaddr;
char sendline[MAXLINE], recvline[MAXLINE];
exit(0);
}
Multitasking – Per-Client Process
For each client connection request, a new process is
Client/sever model
created to handle the communication.
int fork();
A new process is created, identical to the calling
process, except for its process ID and the return value it
receives from fork().
Return 0 to child process, and the process ID of the
new child to parent.
void doprocessing (int sock); /* Now bind the host address using bind()
call.*/
int main( int argc, char *argv[] ) { if (bind(sockfd, (struct sockaddr *)
int sockfd, newsockfd, portno, clilen; &serv_addr, sizeof(serv_addr)) < 0) {
char buffer[256]; perror("ERROR on binding");
struct sockaddr_in serv_addr, cli_addr; exit(1);
int n, pid; }
/* First call to socket() function */ /* Now start listening for the clients,
sockfd = socket(AF_INET, SOCK_STREAM, 0); here process will go in sleep mode and
will wait for the incoming connection
if (sockfd < 0) { */
perror("ERROR opening socket");
exit(1);
}
Multitasking – Per-Client Process
Example: using fork()
listen(sockfd,5); else {
clilen = sizeof(cli_addr); close(newsockfd);
Client/sever model }
while (1) { } /* end of while */
newsockfd = accept(sockfd, (struct }
sockaddr *) &cli_addr, &clilen);
void doprocessing (int sock) {
if (newsockfd < 0) { int n;
perror("ERROR on accept"); char buffer[256];
exit(1); bzero(buffer,256);
} n = read(sock,buffer,255);
if (n < 0) {
perror("ERROR writing to socket");
exit(1);
}
Multitasking – Per-Client Thread
Client/sever
Forkingmodela new process is expensive.
Duplicate the entire state (memory, stack,
file/socket descriptors, ….)
Threads decrease this cost by allowing
multitasking within the same process.
Threads share the same address space (code
and data)
An example is provided using POSIX
Threads
Multitasking – Per-Client Thread
Example: echo using stream socket
Client/sever model
Multitasking – Per-Client Thread
Example: echo using stream socket
Client/sever model
Multitasking – Constrained
Both process and thread incurred overhead.
Client/sever
Creation, model
scheduling and context switching
As their numbers increases:
This overhead increases
After some point it would be better if a client was blocked
Solution: Constrained multitasking. The server:
Begins, creating, binding and listening to a socket
Creates a number of processes, each loop forever and
accept connections from the same socket.
When a connection is established:
The client socket descriptors is returned to only one process.
The other remain blocked.
Multitasking – Constrained
Example: echo using stream socket
Client/sever model
Multiplexing
So far, we have dealt with a single I/O channel.
Client/sever model
We may need to cope with multiple I/O channels.
E.g., supporting the echo service over multiple ports.
Problem: From which socket the server should accept
connections or receive messages?
It can be solved using non-blocking sockets.
But it requires polling
Solution: select()
Specifies a list of descriptors to check for pending I/O
operations.
Blocks until one of the descriptors is ready.
Returns which descriptors are ready.
Multiplexing
Example: echo using stream socket
Client/sever model
Multiplexing
Example: echo using stream socket
Client/sever model
Multiple Recipients
So far, all sockets have dealt with unicast communication.
Client/sever model
i.e., an one-to-one communication, where one copy (“uni”) of the
data is sent (“cast”)
What if we want to send data to multiple recipients?
1st Solution: unicast a copy of data to each recipient
Inefficient, e.g.,
Consider we are connected to the internet through a 3Mbps
line
A video server send 1-Mbps streams
Then, server can support only three clients simultaneously.
2nd Solution: using network support
Broadcast, all the host of the network receive the message.
Multicast, a message is sent to some subset of the host
For IP, only UDP sockets are allowed to broadcast and multicast.
Multiple Recipients
Broadcast
Only the IP address changes
Client/sever model
Local broadcast: to address 255.255.255.255
Send the message to every host on the same broadcast network
Not forwarded by routers
Directed broadcast:
For network identifier 169.125 (i.e., with subnet mask
255.255.0.0)
The directed broadcast address is 169.125.255.255