UNIT 2 TCP ECHO SERVER UNIT 2 UNIT 2 1.
**`getsockname`**: This func@on is used to retrieve the local
#include"unp.h" TCP Echo Client :str_cliFunc4on address and port number of a socket. It is typically called aEer a socket has
Int main(intargc, char**argv) #include"unp.h"
void
been bound to an address using the `bind` func@on. The `getsockname`
{intlistenfd, connfd; str_cli(FILE *fp, intsockfd) func@on takes the socket file descriptor as an argument and fills a `struct
pid_tchildpid; { sockaddr` structure with the local address informa@on.
socklen_tclilen; charsendline[MAXLINE], recvline[MAXLINE];
while(Fgets(sendline, MAXLINE, fp) != NULL) Example:
structsockaddr_in cliaddr, servaddr; { ```c
listenfd = Socket(AF_INET, SOCK_STREAM, 0); Writen(sockfd, sendline, strlen(sendline)); struct sockaddr_storage addr;
bzero(&servaddr, sizeof(servaddr)); if(Readline(sockfd, recvline, MAXLINE) == 0)
err_quit("str_cli: server terminated prematurely"); socklen_t addr_len = sizeof(addr);
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
Fputs(recvline, stdout); getsockname(sockfd, (struct sockaddr *)&addr, &addr_len);
}
servaddr.sin_port = htons(SERV_PORT); }
```
Bind(listenfd, (SA *) &servaddr, sizeof(servaddr)); 2. **`getpeername`**: This func@on is used to retrieve the address and port
Listen(listenfd, LISTENQ); number of the peer socket to which a connec@on-oriented socket is
for( ; ; ) { connected. It is typically called on a connected socket (e.g., aEer a call to
clilen = sizeof(cliaddr); `connect` for TCP sockets). Like `getsockname`, `getpeername` takes the
connfd = Accept(listenfd, (SA *) &cliaddr, &clilen); socket file descriptor as an argument and fills a `struct sockaddr` structure
if( (childpid = Fork()) == 0) { /* child process */ with the peer's address informa@on.
Close(listenfd); /* close listening socket */ Example:
str_echo(connfd); /* process the request */ ```c
exit(0); struct sockaddr_storage addr;
}Close(connfd); /* parent closes connected socket socklen_t addr_len = sizeof(addr);
TCP Echo Server:str_echoFunction getpeername(sockfd, (struct sockaddr *)&addr, &addr_len);
#include"unp.h" The `getsockname` func@on is used to retrieve the local IP address and port
Void str_echo(intsockfd) number assigned to a socket. It is useful aEer a successful `connect` in a TCP
{ ssize_tn; client without a `bind`, aEer calling `bind` with a port number of 0, and in a
charbuf[MAXLINE]; again: TCP server that binds the wildcard IP address to obtain the local IP address
while( (n = read(sockfd, buf, MAXLINE)) > 0) assigned to a connec@on
Writen(sockfd, buf, n); The `getpeername` func@on is used to obtain the address and port number
if(n < 0&& errno == EINTR) of the peer socket in a connected socket. It is useful for iden@fying the client
gotoagain; elseif(n < 0) in a server process that has been `exec`ed by the process calling `accept`.
err_sys("str_echo: read error");
getsockopt and setsockopt Func/ons: sendto() and recvfrom()
•sockfd must refer to an open socket descriptor.
•level specifies the code in the system that interprets the op@on: the general
socket code or some protocol-specific code (e.g., IPv4, IPv6, TCP, or SCTP).
•optval is a pointer to a variable from which the new value of the op@on is
fetched by getsockopt, or into which the current value of the op@on is stored
by setsockopt.
•The size of this variable is specified by the final argument, as a value for
setsockopt and as a value-result for getsockopt.
#include ‹sys/socket.h>
int getsockopt(int sockfd, int level, int optname, void
*optval, socklen_t *optlen);
int setsockopt(int sockfd, int level, int optname, const
1. **`getservbyname`**: This func@on is used to retrieve service informa@on
void *optval socklen_t optlen);
based on a service name and protocol. It takes a service name (e.g., "hfp"
Both return: 0 if OK, 1 on
for HTTP) and a protocol name (e.g., "tcp" for TCP) as arguments and returns
There are two basic types of op@ons:
a pointer to a `struct servent` containing informa@on about the service, such
•binary op@ons that enable or disable a certain feature (flags), and
as its port numbe
•op@ons that fetch and return specific values that we can either set or
Example:
examine (values).
```c
•The column labelled "Flag" specifies if the op@on is a flag op@on.
struct servent *service_info;
•When calling getsockopt for these flag op@ons, *optval is an integer.
service_info = getservbyname("hfp", "tcp");
•The value returned in *optval is zero if the op@on is disabled, or nonzero if
the op@on is enabled. Similarly, setsockopt requires a nonzero *optval to
2. **`getservbyport`**: This func@on is used to retrieve service informa@on
turn the op@on on, and a zero value to turn the op@on off.
based on a port number and protocol. It takes a port number and a protocol
•If the "Flag" column does not contain a "•," then the op@on is used to pass SOCKETR FUNCTION FOR UDP CLIENT AND SERVER UNIT 3 name as arguments and returns a pointer to a `struct servent` containing
a value of the specified datatype between the user process and the system. There are fundamental differences between applica@ons wrifen using TCP informa@on about the service, such as its service name.
versus those that use UDP.
•It is because differences in UDP and TCP protocols. Example:
•UDP is a connec@onless, unreliable, datagram protocol. ```c
•TCP is connec@on-oriented, reliable byte stream. struct servent *service_info;
•Applica@ons built using UDP are: DNS, NFS, and SNMP service_info = getservbyport(htons(80), "tcp")
Domain Name Systems(DNS). The `gethostbyname` and `gethostbyaddr` func@ons are used in network
•The DNS is used primarily to map between hostnames and IP addresses. programming to perform host name resolu@on and obtain informa@on about
•A hostname can be either a simple name, such as solarisor freebsdor a host. Here's a brief explana@on of each:
google.
•A fully qualified domain name (FQDN) such as [Link]. 1. **`gethostbyname`**: This func@on is used to retrieve host informa@on
•An FQDN is also called an absolute name and must end with a DOT, but based on a host name. It takes a host name as an argument and returns a
users oEen omit the ending period. pointer to a `struct hostent` containing informa@on about the host, such as
•The trailing DOT tells the resolver that this name is fully qualified and it its IP addresses.
doesn't need to search its list of possible domains. Example:
```c
Entries in the DNS are known as resource records (RRs). struct hostent *host_info;
•Few types of RRs that are of interest are: host_info = gethostbyname("[Link]");
•A-An A record maps a hostname into a 32-bit IPv4 address.
•AAAA-a AAAA record, called a "quad A" record, maps a hostname into a 2. **`gethostbyaddr`**: This func@on is used to retrieve host informa@on
128-bit IPv6 address. based on an IP address. It takes an IP address in binary form, a length
•The term "quad A" is used because a 128-bit address is four @mes larger indica@ng the size of the address (usually `sizeof(struct in_addr)` for IPv4
than a 32-bit address. addresses), and the address family as arguments. It returns a pointer to a
•PTR -PTR records (called "pointer records") map IP addresses into `struct hostent` containing informa@on about the host
hostnames. PTR records are used for the reverse DNS lookup Example:
Getaddrinfo ```c
struct addrinfo hints, *result; struct hostent *host_info;
memset(&hints, 0, sizeof(hints)); struct in_addr addr;
hints.ai_family = AF_UNSPEC; // Use IPv4 or IPv6 inet_pton(AF_INET, "[Link]", &addr);
hints.ai_socktype = SOCK_STREAM; // Use TCP host_info = gethostbyaddr(&addr, sizeof(addr), AF_INET);
getaddrinfo("[Link]", "hfp", &hints, &result); ```
getaddrinfo: This func@on takes a host name, service name, and a set of
hints (op@onal) as input and returns a linked list of struct addrinfo
structures, each containing informa@on about a single address that can be
used to connect to the specified host and service.
Socket add structure
Concurrent servers are server programs designed to handle mul@ple client fork and exec Func@ons Here are some common socket func@ons used in network programming,
requests simultaneously. These servers are capable of serving mul@ple clients Go, change the world along with their syntax and a brief explana@on:
concurrently without blocking or delaying other clients. There are several •fork() and exec() are used in crea@on of concurrent servers.
approaches to implemen@ng concurrent servers: •The fork func@on returns twice. 1. **`socket`**: Create a new socket.
•It returns once in the calling process (called the parent) with a return value int sockfd = socket(domain, type, protocol);
1. **Mul@-Process Servers**: Each client connec@on is handled by a separate that is the process ID of the newly created process (the child). - `domain`: Address family (e.g., `AF_INET` for IPv4).
process. The server creates a new process or thread for each incoming •It also returns once in the child, with a return value of 0. - `type`: Socket type (e.g., `SOCK_STREAM` for TCP).
connec@on, allowing mul@ple clients to be served concurrently. •The return value tells the process whether it is the parent or the child. - `protocol`: Specific protocol (usually set to 0 for default)
•All descriptors open in the parent before the call to fork are shared with the 2. **`bind`**: Bind a socket to an address and port.
2. **Mul@-Threaded Servers**: Similar to mul@-process servers, but uses child aEer fork returns. int status = bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
threads instead of processes to handle client connec@ons. Threads share the - `sockfd`: Socket file descriptor.
same address space, making them more lightweight than processes. - `addr`: Address structure (`struct sockaddr`)
3. **`listen`**: Set a socket to listen for incoming connec@ons.
3. **Event-Driven Servers**: These servers use a single-threaded event loop int status = listen(sockfd, backlog);
to manage mul@ple client connec@ons. Events, such as incoming data or - `backlog`: Maximum number of pending connec@ons.
client connec@ons, are processed asynchronously, allowing the server to 4. **`accept`**: Accept a connec@on on a socket.
handle mul@ple clients concurrently without crea@ng addi@onal threads or •In network servers, the parent calls accept and then calls fork. int new_sockfd = accept(sockfd, (struct sockaddr *)&addr, &addrlen);
processes. •The connected socket is then shared between the parent and child. - `new_sockfd`: New socket file descriptor for the accepted connec@on.
•Normally, the child then reads and writes the connected socket and the - `addr`: Address structure of the client.
4. **Thread Pool Servers**: These servers maintain a pool of threads that parent closes the connected socket. - `addrlen`: Pointer to the size of `addr`.
are used to handle client connec@ons. When a new connec@on arrives, a •There are two typical uses of fork: 5. **`connect`**: Ini@ate a connec@on to a remote host.
thread from the pool is assigned to handle it. This approach reduces the 1.A process makes a copy of itself so that one copy can handle one opera@on
overhead of crea@ng and destroying threads for each client connec@on. while the other copy does another task. int status = connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));
2.A process wants to execute another program. Since the only way to create 6. **`send`**: Send data over a socket.
Concurrent servers are commonly used in applica@ons where mul@ple clients a new process is by calling fork, the process first calls fork to make a copy of ssize_t bytes_sent = send(sockfd, buffer, length, flags)
need to interact with a server simultaneously, such as web servers, chat itself, and then one of the copies (typically the child process) calls exec 7. **`recv`**: Receive data from a socket.
servers, and online gaming servers. They provide efficient and scalable (described next) to replace itself with the new program. ```c
solu@ons for handling concurrent client requests. ssize_t bytes_received = recv(sockfd, buffer, length, flags);
8. **`close`**: Close a socket
int status = close(sockfd)
Comparison of TCP, UDP, and SCTP:
1. TCP (Transmission Control Protocol):
o Connection-oriented: Establishes a connection before data transfer.
o Reliability: Ensures reliable, ordered delivery of data.
o Flow control: Adjusts the rate of data transmission based on network
conditions.
o Error checking: Includes error detection and correction mechanisms.
o Congestion control: Manages data transmission to prevent network
congestion.
o Examples: Used for applications like web browsing, email, file
transfer (e.g., HTTP, SMTP, FTP).
2. UDP (User Datagram Protocol):
o Connectionless: Does not establish a connection before data transfer.
o Unreliable: Does not guarantee reliable, ordered delivery of data.
o Low overhead: Provides minimal error checking and no flow or
congestion control.
o Examples: Used for real-time applications where speed is more
important than reliability, such as online gaming, VoIP, DNS.
3. SCTP (Stream Control Transmission Protocol):
o Connection-oriented: Establishes a connection before data transfer.
o Message-oriented: Sends data in messages, preserving message
boundaries.
o Reliability: Provides reliable, ordered delivery of data, but also
supports partial delivery.
o Multi-streaming: Allows for multiple streams of data within a single
connection.
o Multi-homing: Supports connections to multiple IP addresses,
providing fault tolerance and network redundancy.
o Error detection: Includes built-in checksums for error detection.
o Congestion control: Manages data transmission to prevent network
congestion.
o Examples: Used for applications requiring reliable, high-
performance communication, such as telephony, signaling, and IP
telephony.
. UNIT 1
TCP STATE TRANSITION DIAGRAM. UNIT 1
Features of SCTP: . UNIT 1
. UNIT 1. IPV4 SOCKET
. UNIT 1
• Multi-streaming: Allows for multiple streams of data within a single
Most socket functions require a pointer to a socket address
connection, improving efficiency for applications that need to
transfer multiple streams of data simultaneously. structure as an argument.
• Multi-homing: Supports connections to multiple IP addresses, [Link] supported protocol suite defines its own socket
providing fault tolerance and network redundancy. address structure.
• Partial delivery: Enables the receiver to extract partial data from a
[Link] names of these structures begin with sockaddr_ and
message, useful for large messages or real-time applications.
• Reliability: Provides reliable, ordered delivery of data with error end with a unique suffix for each protocol suite.
detection and correction mechanisms. IPv4 Socket Address Structure
• Congestion control: Manages data transmission to avoid network An IPv4 socket address structure, commonly called an
congestion and ensure fair sharing of network resources.
"Internet socket address structure," is named sockaddr_in
and is defined by including the header.
struct in_addr {
in_addr_t s_addr; /* 32-bit IPv4 address */
/* network byte ordered */
};
Struct sockaddr_in {
The following scenario occurs when a TCP connection is established:
uint8_t sin_len;/* length of structure (16)
[Link] server must be prepared to accept an incoming connection. This is normally
done by calling socket, bind, and listen and is called a passive open.
*/
[Link] client issues an active open by calling connect. This causes the client TCP to
send a "synchronize" (SYN) segment, which tells the server the client's initial
sa_family_t sin_family; /* AF_INET */
sequence number for the data that the client will send on the connection. Normally,
there is no data sent with the SYN; it just contains an IP header, a TCP header, and
in_port_tsin_port; /* 16-bit TCP or
possible TCP options (which we will talk about shortly). UDP port number network byte ordered
[Link] server must acknowledge (ACK) the client's SYN and the server must also send
its own SYN containing the initial sequence number for the data that the server will */
4 way hand shake send on the connection. The server sends its SYN and the ACK of the client's SYN in
The following scenario occurs when a TCP connection is established: a single segment. struct in_addr sin_addr; /* 32-bit IPv4
[Link] application calls close first, and we say that this end performs the active close. This end's TCP sends a [Link] client must acknowledge the server's SYN.
FIN segment, which means it is finished sending data.
[Link] other end that receives the FIN performs the passive close. The received FIN is acknowledged by
address network byte ordered */
TCP. The receipt of the FIN is also passed to the application as an end-of-file (after any data that may have
already been queued for the application to receive), since the receipt of the FIN means the application will
char sin_zero[8]; /* unused */ };
UNIT 5 TLS (Transport Layer Security)
•IETF standard RFC 2246 similar to SSLv3
IEE 802.11
•with minor differences
Transition types, based on mobility: [Link] record format version number
•No transition-A station of this type is either stationary or moves only within the direct [Link] HMAC for MAC
communication range of the communicating stations of a single BSS iii.a pseudo-random function expands secrets
BSS transition•Station movement from one BSS to another BSS within the same ESS; [Link] on HMAC using SHA-1 or MD5
delivery of data to the station requires that the addressing capability be able to [Link] additional alert codes
recognize the new location of the station [Link] changes in supported ciphers
•ESS transition-Station movement from a BSS in one ESS to a BSS within another [Link] in certificate types & negotiations
ESS; maintenance of upper-layer connections supported by 802.11 cannot be guarantee [Link] in crypto computations & padding
Access point Any entity that has station functionality and provides
(AP) access to the distribution system via the wireless medium
for associated stations.
Basic service A set of stations controlled by a single coordination
set (BSS) function.
Coordination The logical function that determines when a station
function operating within a BSS is permitted to transmit and may
be able to receive PDUs.
Distribution A system used to interconnect a set of BSSs and
system (DS) integrated LANs to create an ESS.
Extended A set of one or more interconnected BSSs and integrated
service set LANs that appear as a single BSS to the LLC layer at
(ESS) any station associated with one of these BSSs.
MAC protocol The unit of data exchanged between two peer MAC
data unit entities using the services of the physical layer.
(MPDU)
MAC service Information that is delivered as a unit between MAC
data unit users.
(MSDU)
Station Any device that contains an IEEE 802.11 conformant
MAC and physical
eLEMENT OF IEE802.11
ROBOUST SECURE NETWORK. Security in networks can be achieved using
various techniques, including robust secure network design, which focuses on
building resilient and secure networks. Here are some key principles and
technologies used to achieve security in robust secure networks:
1. **Encryption**: Encrypting data ensures that even if it's intercepted, it cannot
be read without the encryption key. Protocols like TLS (Transport Layer Security)
and IPsec (Internet Protocol Security) are used to encrypt data in transit.
2. **Firewalls**: Firewalls are used to monitor and control incoming and
outgoing network traffic based on predetermined security rules. They act as a
barrier between secure internal networks and untrusted external networks.
3. **Intrusion Detection and Prevention Systems (IDPS)**: These systems
monitor network traffic for suspicious activity or known threats. They can detect
and block malicious traffic in real time.
SSL Record Protocol Services
[Link] 4. **Access Control**: Access control mechanisms ensure that only authorized
•using symmetric encryption with a shared secret key defined by
Handshake Protocol
users and devices can access the network and its resources. This includes using
•AES, IDEA, RC2-40, DES-40, DES, 3DES, Fortezza, RC4-40, RC4-128 strong authentication mechanisms like multi-factor authentication (MFA) and
•message is compressed before encryption role-based access control (RBAC).
[Link] integrity
[Link] a MAC with shared secret key 5. **Network Segmentation**: Dividing a network into smaller segments helps
[Link] to HMAC but with different padding contain breaches and limit the impact of a security incident. This can be achieved
SSL Change Cipher Spec Protocol using VLANs (Virtual Local Area Networks) or subnetting.
•one of 3 SSL specific protocols which use the SSL Record
protocol a single message causes pending state to become current 6. **Regular Updates and Patching**: Keeping network devices and software up
hence updating the cipher suite in use to date with the latest security patches helps protect against known vulnerabilities.
SSL Alert Protocol
Øconveys SSL-related alerts to peer entity,severity 7. **Security Policies and Procedures**: Establishing and enforcing security
•warning or fatal,specific alert policies and procedures helps ensure that security measures are consistently
•fatal: unexpected message, bad record mac, decompression applied and maintained.
failure, handshake failure, illegal parameter
•warning: close notify, no certificate, bad certificate, unsupported 8. **Redundancy and Failover**: Building redundancy and failover mechanisms
certificate, certificate revoked, certificate expired, certificate into the network ensures that even if one part of the network fails or is
unknown compromised, the network can continue to operate securely.
Øcompressed & encrypted like all SSL data