Unit-8 - Advanced Socket Options
Unit-8 - Advanced Socket Options
Source: UNIX Network Programming: Chapter: 13 W. Richard Stevens, Bill Fenner, Andrew M. Rudoff
Overview
● Daemon Process
● Internet Group Management Protocol - Group management
● IGMP Messages
● IGMP operation
● Encapsulation
● Raw Sockets
● Streams
2
Chapter 13.
3
Daemons
A daemon is a process that:
Runs in the background
Not associated with any terminal- No user interaction is required
5
Windows
6
Contd..
7
Contd..
8
Introduction
● A daemon is a process that runs in the background and is independent of control from all terminals.
● There are numerous ways to start a daemon
The system initialization scripts
Many network servers are started by the inetd superserver.
The execution of programs on a regular basis is performed by the cron daemon
The execution of a program at one time in the future is specified by the at command.
Daemons can be started from user terminals, either in the foreground or in the background.
● Since a daemon does not have a controlling terminal, it needs some way to output message when
something happens, either normal informational messages, or emergency messages that need to be
handled by an administrator.
● Systems often start daemons at boot time and serve the function of responding to network requests,
hardware activity, or other programs by performing some task.
● The syslog function is standard way to output these messages , and it sends the message to the
syslogd daemon. 9
Common Daemons
● Web server (httpd)
● Mail server (sendmail)
● SuperServer (inetd)
● System logging (syslogd)
● Print server (lpd) is a network protocol for submitting print jobs
To a remote printer
● router process (routed, gated)
10
Syslog
● Syslog is one of the most important standards used in Linux.
● It is the key file which helps you determine the different level of logs which are getting
generated and stored every second while you are working on your Linux box.
● Syslog can be taken as "System Log".
Benefits of syslog
● Helps analyze the root cause for any trouble or problem caused
● Reduce overall downtime helping to troubleshoot issues faster with all the logs
● Improves incident management by active detection of issues
● Self-determination of incidents along with auto resolution
● Simplified architecture with different level of severity like error,info,warning etc.
11
Syslog servers
● A Syslog listener: A Syslog server needs to receive messages sent over the network. A
listener process gathers syslog data sent over UDP port 514. UDP messages aren’t
acknowledged or guaranteed to arrive, so be aware that some network devices will send
Syslog data via TCP 1468 to ensure message delivery.
● A database: Large networks can generate a huge amount of Syslog data. Good Syslog
servers will use a database to store syslog data for quick retrieval.
12
syslogd daemon
● Unix system normally starts a daemon named syslogd from one of the system initialization
scripts, and it runs as long as the system is up.
● Berkeley-derived implementation of syslogd perform the following actions upon startup.
The configuration file /etc/syslog.conf, is read, specifying what to do with each type of log message that the
daemon can receive.
A Unix domain socket is created and bound to the pathname /var/run/log ( /dev/log on some system).
A UDP socket is created and bound to port 514
The pathname /dev/klog is opened. Any error messages from within the kernel appear as input on this
device.
● We could send log messages to the syslogd daemon from our daemons by creating a Unix
domain datagram socket and sending our messages to the pathname that the daemon has
bound, but an easier interface is the syslog function.
13
Contd..
14
15
Contd.. https://linuxhandbook.com/syslog-guide/
16
Contd..
17
syslog function
● Since daemon does not have a controlling terminal, it cannot just fprintf to stderr. The
common technique to logging message from a daemon is to call the syslog function.
#include <syslog.h>
Void syslog(int priority, const char *message, . . . );
18
syslog function
● Log message have a level between 0 and 7. If no level is specified by the sender ,
LOG_NOTICE is the default.
level value description
LOG_EMERG 0 system is unusable ( highest priority )
LOG_ALERT 1 action must be taken immediately
LOG_CRIT 2 critical conditions
LOG_ERR 3 error conditions
LOG_WARNING 4 warning conditions
LOG_NOTICE 5 normal but significant condition (default)
LOG_INFO 6 informational
LOG_DEBUG 7 debug-level message ( lowest priority )
Figure 12.1 level of log message.
19
Contd..
20
Contd..
21
syslog function
● A facility to identify the type of process sending the message.
22
syslog function
● When the application calls syslog the first time, it creates a Unix domain datagram socket
and then calls connect to the well known pathname of the socket created by the syslogd
daemon.
● Openlog and closelog
openlog can be called before the first call to syslog and closelog can be called when the application is
finished sending log messages.
The option argument is formed as the logical OR of one or more of the constants shown in tables.
Ident – is a string that will be prepended to each log message by syslog
options Description
#include <syslog.h>
LOG_CONS Log to console if cannot send to syslog daemon
void openlog(const char *ident, int options, int facility); LOG_NDELAY Do not delay open, create socket now
LOG_PERROR Log to standard error as well as sending
void closelog(void);
to syslog daemon
LOG_PDI Log the process ID with each message
23
Contd..
● A daemon is started either by the system itself or a user in a terminal or script. When it does
start, the process is just like any other executable on the system. To make it truly
autonomous, a child process must be created where the actual code is executed. This is
known as forking, and it uses the fork() function:
24
daemon_init Function
#include "unp.h"
#include <syslog.h>
#define MAXFD 64
extern int daemon_proc; /* defined in error.c */
void daemon_init(const char *pname, int facility)
{
int i;
pid_t pid;
if ( (pid = Fork()) != 0)
exit(0); /* parent terminates */
25
/* 2nd child continues */
daemon_proc = 1; /* for our err_XXX() functions */
chdir("/"); /* change working directory */
umask(0); /* clear our file mode creation mask */
26
Contd..
27
Too many daemons?
● There can be many servers running as daemons - and idle most of the time.
● Much of the startup code is the same for these servers.
● Most of the servers are asleep most of the time, but use up space in the process table.
28
SuperServer
● Most Unix systems provide a “SuperServer” that solves the problem:
Executes the startup code required by a bunch of servers.
Waits for incoming requests destined for the same bunch of servers.
When a request arrives - starts up the right server and gives it the request.
29
inetd Daemon
● A typical Unix system’s problems
1. All these daemons contained nearly identical startup code.
2. Each daemon took a slot in the process table, but each daemon was asleep most of the time.
● inetd daemon fixes the two problems.
1. It simplifies writing daemon processes, since most of the startup details are handled by inetd.
2. It allow a single process(inetd) to be waiting for incoming client requests for multiple services, instead of
one process for each service.
30
Steps performed by inetd
● On startup, it reads the /etc/inetd.conf file and creates a socket of the appropriate type
(stream or datagram) for all the services specified in the file. The maximum number of
servers that inetd can handle depends on the maximum number of descriptors that inetd can
create. Each new socket is added to a descriptor set that will be used in a call to select.
● Bind is called for the socket, specifying the port for the server and the wildcard IP address.
This TCP or UDP port number is obtained by calling getservbyname with the service-name
and protocol fields from the configuration file as arguments.
● For TCP sockets, listen is called so that incoming connection requests are accepted. This
step is not done for datagram sockets.
● After all the sockets are created, select is called to wait for any of the sockets to become
readable. listening TCP socket becomes readable when a new connection is ready to be
accepted and a UDP socket becomes readable when a datagram arrives. inetd spends most
of its time blocked in this call to select, waiting for a socket to be readable.
32
Contd..
● When select returns that a socket is readable, if the socket is a TCP socket and the nowait
flag is given, accept is called to accept the new connection.
● The inetd daemon forks and the child process handles the service request. This is similar to
a standard concurrent server.
● If the socket is a stream socket, the parent process must close the connected socket (like our
standard concurrent server). The parent calls select again, waiting for the next socket to
become readable.
33
socket()
12.5 inetd daemon bind() F o r eac h s ervic e lis ted in the
/etc/inetd.conf file
select()
fo r re a d a b ility
accpet()
( if TC P so c k e t)
fork()
parent child
dup so c k e t to d e sc rip to rs
0 ,1 a n d 2 ;
close so c k e t
setgid()
setuid()
( if u se r n o t ro o t)
exec() se rve r 34
35
example /etc/inetd.conf
service-name socket-type protocol wait-flag login-name server-program server-program-
argument
# comments start with #
echo stream tcp nowait root internal
echo dgram udp wait root internal
chargen stream tcp nowait root internal
chargen dgram udp wait root internal
ftp stream tcp nowait root /usr/sbin/ftpd ftpd -l
telnet stream tcp nowait root /usr/sbin/telnetd telnetd
finger stream tcp nowait root /usr/sbin/fingerd fingerd
# Authentication
auth stream tcp nowait nobody /usr/sbin/in.identd in.identd -l -e –o
# TFTP
tftp dgram udp wait root /usr/sbin/tftpd tftpd -s /tftpboot
36
Contd..
37
12.6 daemon_inetd Function
● Figure 12.11
#include "unp.h"
#include <syslog.h>
40
UNICASTING
41
41
MULTICASTING
4
2
42
Difference b/w multicasting and multiple unicasting
■ Multicasting starts with one single packet from the source that is duplicated by the routers.
The destination address in each packet is the same for all duplicates
■ In multiple unicasting, several packets start from the source with different destination
address. For example, when a person sends an e-mail message to a group of people, this is
multiple unicasting.
■ The e-mail software creates replicas of the message, each with a different destination
address, and sends them one by one.
43
Applications of Multicasting
● Teleconferencing
● Distance Learning
● Dissemination of News
4
4
44
Multicast Address
● A multicast address is a destination address for a group of hosts that have joined a multicast
group.
● A packet that uses a multicast address as a destination can reach all members of the group
unless there are some filtering restriction by the receiver.
● Multicast Address used in IPV4: In classful addressing, multicast addresses occupied the
only single block in class D. In classless addressing the same block has been used for this
purpose.
● In other words, the block assigned for multicasting is 224.0.0.0/4. This means that the
block has 2^28 = 268,435,456 addresses (224.0.0.0 to 239.255.255.255).
45
Internet Group Management Protocol (IGMP)
● Multicast communication means that a sender sends a message to a group of recipients that
are members of the same group.
● Since one copy of the message is sent by the sender, but copied and forwarded by routers,
each multicast router needs to know the list of groups that have at least one loyal member
related to each interface.
● This means that the multicast routers need to collect information about members and share
it with other multicast routers.
● Collection of this type of information is done at two levels: locally and globally.
● A multicast router connected to a network is responsible to collect this type of information
locally; the information collected can be globally propagated to other routers.
● The first task is done by the IGMP protocol; the second task is done by the multicast
routing protocols.
46
Position of IGMP in the network layer
4
7
47
GROUP MANAGEMENT
48
Note:
1
0
49
IGMP Versions
● IGMP has gone through three versions. Versions 1 and 2 provide what is called any source
multicast (ASM), which means that the group members receive a multicast message no
matter where it comes from.
● The IGMP version 3 provides what is called source specific multicast (SSM), which means
that the recipient can choose to receive multicast messages coming from a list of predefined
sources.
● In this section we discuss only IGMPv3.
50
IGMP MESSAGES
● IGMP has three types of messages: the query, the membership report, and the leave report.
51
IGMP message format
52
IGMP OPERATION
● A multicast router connected to a network has a list of multicast addresses of the groups
with at least one loyal member in that network.
● For each group, there is one router that has the duty of distributing the multicast
packets destined for that group.
● The topics discussed in this section include:
● Joining a Group Leaving a Group Monitoring Membership
53
Membership report
Note:
● In IGMP, a membership report is sent twice, one after the other.
54
Contd..
● Type. This 8-bit field defines the type of the message. The value is 0X11 for a membership
query message.
● Maximum Response Code. This 8-bit field is used to define the response time of a
recipient of the query as we will show shortly.
● Checksum. This is a 16-bit field holding the checksum. The checksum is calculated over
the whole IGMP message.
● Group Address. This 32-bit field is set to 0 in a general query message; it is set to IP
multicast being queried when sending a group-specific or group-and-source specific query
message.
55
Contd..
● Resv. This 4-bit field is reserved for the future and it is not used.
● S. This is a 1-bit suppress flag. When this field is set to 1, it means that the receivers of the
query message should suppress the normal timer updates.
● QRV. This 3-bit field is called querier’s robustness variable. It is used to monitor the
robustness in the network.
● QQIC. This 8-bit field is called querier’s query interval code. This is used to calculate the
querier’s query interval (QQI), as we will show shortly.
● Number of sources (N). This 16-bit field defines the number of 32-bit unicast source
addresses attached to the query. The value of this field is zero for the general query and the
group-specific query, and nonzero in the group-and-source-specific query.
● Source Addresses. These multiple 32-bit fields list the N source addresses, the origin of
multicast messages. The value of N is defined in the previous field.
56
Leave report
57
General query message
Note:
● The general query message does not define a particular group.
58
Contd..
● In a general query message, the querier router probes each neighbor to report the whole list
of its group membership (interest in any multicast group).
● In a group-specific query message, the querier router probes each neighbor to report if it is
still interested in a specific multicast group. The multicast group address is defined as x.y.z.t
in the group address field of the query.
● In a group-and-source-specific query message, the querier router probes each neighbor to
report if it is still in a specific multicast group, x.y.z.t, coming from any of the N sources
whose unicast addresses are defined in this packet.
59
Example
●Imagine there are three hosts in a network as shown in Figure 10.8.
●A query message was received at time 0; the random delay time (in tenths of seconds) for
each group is shown next to the group address. Show the sequence of report messages.
60
Contd..
Solution
●The events occur in this sequence:
Time 12: The timer for 228.42.0.0 in host A expires and a membership report is sent, which is received by
the router and every host including host B which cancels its timer for 228.42.0.0.
Time 30: The timer for 225.14.0.0 in host A expires and a membership report is sent, which is received by
the router and every host including host C which cancels its timer for 225.14.0.0.
Time 50: The timer for 238.71.0.0 in host B expires and a membership report is sent, which is received by
the router and every host.
Time 70: The timer for 230.43.0.0 in host C expires and a membership report is sent, which is received by
the router and every host including host A which cancels its timer for 230.43.0.0.
● Note that if each host had sent a report for every group in its list, there would have been
seven reports; with this strategy only four reports are sent.
61
Note:
• The IP packet that carries an IGMP packet has a value of 2 in its protocol field.
• The IP packet that carries an IGMP packet has a value of 1 in its TTL field.
62
Destination IP addresses
63
Contd..
64
RAW SOCKETS
(+ OTHER)
Chapter 28
66
67
68
Other –
● Readv ( ) and writev ( )
Read or write data into multiple buffers
Connection-oriented.
69
What are Raw Sockets?
1. A way to pass information to network protocols other than TCP or UDP (e.g. ICMP and
IGMP)
2. A way to implement new IPv4 protocols
3. A way to build our own packets (be careful here)
81
Why Would We Use Them?
● Allows us to access packets sent over protocols other than TCP / UDP
● Allows us to process IPv4 protocols in user space
Control, speed, troubleshooting
● Allow us to implement new IPv4 protocols
● Allows us to control the IP header
Control option fields (beyond setsockopt() )
Test / control packet fragmentation
82
Limitations?
● Reliability Loss
● No Ports
● Nonstandard communication
● No Automatic ICMP
● Raw TCP / UDP unlikely
● Requires root / admin
83
Raw Sockets Operation (ICMP)
● Create a socket
s = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP)
● Send / Receive data
Place data to be sent into buffer
sendto (s, buf, strlen(buf), 0, addr, &len);
* More later
85
Raw Sockets Operation (ICMP)
86
Create a Raw Socket
● s = socket (AF_INET, SOCK_RAW, protocol)
IPPROTO_ICMP, IPPROTO_IP, etc.
● Can “bind”
Since we have no port, the only effect is to associate a local IP address with the raw socket. (useful if there
are multiple local IP addrs and we want to use only 1).
● Can “connect”
Again, since we have no TCP, we have no connection. The only effect is to associate a remote IP address
with this socket.
87
Raw Socket Output
● Normal output performed using sendto or sendmsg.
Write or send can be used if the socket has been connected
● If IP_HDRINCL not set, starting addr of the data (buf) specifies the first byte following the
IP header that the kernel will build.
Size only includes the data above the IP header.
● If IP_HDRINCL is set, the starting addr of the data identifies the first byte of the IP header.
Size includes the IP header
Set IP id field to 0 (tells kernel to set this field)
Kernel will calculate IP checksum
88
Raw Socket Input
● Received TCP / UDP NEVER passed to a raw socket.
● Most ICMP packets are passed to a raw socket
(Some exceptions for Berkeley-derived implementations)
89
Normal Socket Operation (TCP)
90
OS Involvement in Sockets
Socket ( AF_INET,
SOCK_STREAM, Identify TCP
IPPROTO_TCP) Socket Type
Socket ( AF_INET,
SOCK_RAW, Identify IP
IPPROTO_ICMP) Socket Type
Socket ( AF_PACKET,
SOCK_RAW, Identify Ethernet
htons(ETH_P_IP)) Socket Type
91
Conditions that include / exclude passing to specific raw sockets
● If a nonzero protocol is specified when raw socket is created, datagram protocol must match
● If raw socket is bound to a specific local IP, then destination IP must match
● If raw socket is “connected” to a foreign IP address, then the source IP address must match
92
Summary
● Raw Sockets allow access to Protocols other than the standard TCP and UDP
● Performance and capabilities may be OS dependent.
Some OSs block the ability to send packets that originate from raw sockets (although reception may be
permitted).
● Raw sockets remove the burden of the complex TCP/IP protocol stack, but they also
remove the safeguards and support that those protocols provide
103
Full Duplex Communication Client -UDP
void main() { //printf("%i", sockd);
if(sentbytes==-1)
close(sockd);
104
int pid = fork(); else{
while(1) { //for(i=0;i<10000;i++);
//printf("\nEnter the name of the file\n"); rvdbytes=recvfrom(sockd, buff, sizeof(buff), 0,
(struct sockaddr*)&serveraddr, &actlen);
if(pid == 0) {
puts(buff);
gets(buff);
printf("\n");
sentbytes=sendto(sockd, buff, sizeof(buff), 0,
if(strcmp(buff,"BYE")==0) {
(struct sockaddr*)&serveraddr, sizeof(serveraddr));
kill(getpid(), sig);
if(sentbytes==-1)
break;
close(sockd); }
if(strcmp(buff,"BYE")==0) { }
kill(getpid(), sig); }
break; close(sockd);
}} }
105
Full Duplex Communication Client -Server
void main(){ sockd=socket(AF_INET, SOCK_DGRAM, 0);