Network Programming Notes Module-02
Network Programming Notes Module-02
1. Sockets Introduction:
Socket in Computer Network
A socket is one endpoint of a two way communication link between two
programs running on the network. The socket mechanism provides a means of
inter-process communication (IPC) by establishing named contact points
between which the communication take place.
Types of Sockets
There are two types of Sockets:
Datagram Socket : This is a type of network which has connection less
point for sending and receiving packets. It is similar to mailbox. The
letters (data) posted into the box are collected and delivered (transmitted)
to a letterbox (receiving socket).
Stream Socket In Computer operating system, a stream socket is type
of interprocess communications socket or network socket which
provides a connection-oriented, sequenced, and unique flow of data
without record boundaries with well defined mechanisms for creating
and destroying connections and for detecting errors. It is similar to
phone. A connection is established between the phones (two ends) and a
conversation (transfer of data) takes place.
Common Function Calls in Socket Programming
Here is a summary of the common function calls used in socket
programming:
Function Call Description
contact
Example:
Consider an IPv4 socket. Its address is represented by
the sockaddr_in structure, which includes:
struct sockaddr_in {
sa_family_t sin_family; // Address family (AF_INET)
in_port_t sin_port; // Port number
struct in_addr sin_addr; // IPv4 address
unsigned char sin_zero[8]; // Padding to make structure same size as
sockaddr
};
How it's used:
Socket functions like bind, connect, accept, and sendto take
a sockaddr (or a pointer to a protocol-specific structure) as an argument.
The application provides the socket address structure to these functions,
which then use it to establish connections, send data, or receive data
from the specified address.
When working with different address families, applications often need
to cast the generic sockaddr pointer to the correct protocol-specific
structure (e.g., sockaddr_in for IPv4).
In essence, socket address structures are the fundamental way that
applications identify and interact with network endpoints.
3. value-result arguments:
In network programming, a value-result argument is a parameter passed to a
function where the function both receives an initial value from the caller and
returns a modified value back to the caller. This is particularly useful in socket
programming where you need to pass a socket address structure and its length,
and the function needs to both receive the initial size of the buffer (for receiving
data) and return the actual size of the data received.
Here's a breakdown:
Value:
The initial value of the argument is used by the function. For example, when
calling getpeername() to retrieve the address of a connected peer, you pass the
size of your buffer as an argument.
Result:
The function modifies the argument and returns the updated value. In
the getpeername() example, the function modifies the length argument to
reflect the actual size of the peer's address that was received.
Example:
accept() in socket programming is a prime example. You pass the size of
your sockaddr_in structure to accept(). The function then fills the structure
with the client's address and updates the length argument with the actual size
of the address.
Why use it?
Value-result arguments are convenient because they allow a single parameter
to convey both input and output information to the function, avoiding the need
for separate input and output parameters or return values.
In simpler terms, imagine you have a container (the argument) and you want a
function to fill it with something, but you also need to know how much was
actually put in the container. You pass the empty container (its size) and the
function returns the filled container (and the updated size).
4. byte ordering and manipulation functions:
In network programming, byte ordering (also known as endianness) and
manipulation functions are crucial for ensuring that multi-byte data is
interpreted correctly when transmitted between systems with different
architectures. Network protocols generally use big-endian byte order, while
many systems (like Intel x86) use little-endian. Functions
like htons, htonl, ntohs, and ntohl are used to convert between host and
network byte order, preventing data corruption during communication.
Byte Ordering:
Big-Endian: Stores the most significant byte at the lowest memory address.
Little-Endian: Stores the least significant byte at the lowest memory
address.
Network Byte Order:
Network protocols, like TCP/IP, typically use big-endian byte order for
transmitting multi-byte data like port numbers, IP addresses, and other
network-related information.
Byte Ordering Functions:
htons(hostshort): Converts a 16-bit (2-byte) quantity from host byte order to
network byte order (big-endian).
htonl(hostlong): Converts a 32-bit (4-byte) quantity from host byte order to
network byte order (big-endian).
ntohs(netshort): Converts a 16-bit quantity from network byte order to host
byte order.
ntohl(netlong): Converts a 32-bit quantity from network byte order to host
byte order.
Byte Manipulation Functions:
memcpy(dest, src, n): Copies n bytes from the memory location pointed to
by src to the memory location pointed to by dest.
memset(dest, c, n): Fills the first n bytes of the memory location pointed to
by dest with the byte value c.
memcmp(ptr1, ptr2, n): Compares the first n bytes of the memory locations
pointed to by ptr1 and ptr2.
bcopy(src, dest, n): Copies n bytes from src to dest.
bzero(dest, n): Sets the first n bytes of the memory location pointed to
by dest to 0.
bcmp(ptr1, ptr2, n): Compares the first n bytes of the memory locations
pointed to by ptr1 and ptr2.
Why are these functions important?
int main() {
const char *ipv4_address_str = "192.168.1.100";
struct in_addr ipv4_addr;
char buffer[INET_ADDRSTRLEN];
// Convert binary IPv4 address to string
if (inet_ntop(AF_INET, &ipv4_addr, buffer, INET_ADDRSTRLEN) ==
NULL) {
perror("inet_ntop failed");
return 1;
}
printf("String IPv4 address: %s\n", buffer);
return 0;
}
Key Considerations:
IPv4 vs. IPv6:
inet_pton and inet_ntop are the preferred functions as they handle both IPv4
and IPv6 addresses.
Network Byte Order:
Address conversion functions typically operate in network byte order (big-
endian), which is the standard for network communication.
Error Handling:
Always check the return values of these functions to ensure successful
address conversion and handle errors appropriately
6.Elementary TCP sockets:
Elementary TCP sockets in network programming involve a set of system
calls that enable communication between applications over a network using
the Transmission Control Protocol (TCP). These calls handle the creation,
connection, data transfer, and termination of TCP connections.
Here's a breakdown of the key concepts and functions:
1. Socket Creation:
socket(): This function is the first step in creating a socket. It takes
parameters specifying the address family (e.g., AF_INET for IPv4),
socket type (e.g., SOCK_STREAM for TCP), and protocol (usually 0 for
TCP). It returns a file descriptor (an integer) that represents the socket.
2. Server-Side Operations:
bind(): This function associates a local address (IP address and port
number) with the socket. Servers typically bind to a well-known port that
clients can connect to.
listen(): This function puts the server socket into a passive listening state,
indicating that it's ready to accept incoming connection requests.
accept(): This function blocks until a client connects to the server's
socket. It then creates a new socket (a "connected socket") for
communication with that specific client, returning a new file descriptor.
3. Client-Side Operations:
connect(): This function initiates a connection to a server. It takes the
server's address information as input and attempts to establish a TCP
connection.
4. Data Transfer:
read(): This function reads data from a connected socket.
write(): This function sends data to a connected socket.
5. Connection Termination:
close(): This function closes the socket, releasing the associated
resources.
Example Scenario:
A TCP server would typically:
1. Create a socket using socket().
2. Bind the socket to a specific address and port using bind().
3. Put the socket into a listening state using listen().
4. Enter a loop:
o Accept a connection using accept().
o Communicate with the client using read() and write().
o Close the connected socket using close().
Fig: Elementary TCP sockets
print(f'Received {data!r}')
Explanation:
Sockets:
Sockets are the endpoints of a two-way communication link between programs.
TCP:
TCP (Transmission Control Protocol) is a connection-oriented protocol that
ensures reliable, ordered, and error-checked delivery of data.
Client-Server Model:
The server listens for incoming connections on a specific port, while the client
initiates a connection to that port.
Connection Establishment:
The server uses bind() to associate the socket with a specific address and
port, listen() to wait for incoming connections, and accept() to accept a
connection.
Data Exchange:
Once connected, the client and server can use sendall() to send data
and recv() to receive data.
Echo Server:
In this example, the server simply sends back whatever it receives,
demonstrating a basic data exchange.