4. Socket Function
• To perform network I/O .
• Family specifies the protocol family.
5. The connect function is used by a TCP client to
establish a connection with a TCP server:
Sockfd is a socket descriptor returned by the socket
function
Second & Third arguments are a pointer to the socket
address structure and its size.
6. The socket address structure must contain –
IP address
Port number
The client does not have to call bind.
The kernel chooses both an temporary port
and the source IP address if necessary.
8. • Assigns a local protocol address to a socket.
• With IP, the protocol address is the combination of 32-bit IPv4 or
128-bit IPv6 address, along with a 16-bit TCP or UDP port
number.
#include <sys/socket.h>
int bind(int sockfd, const struct sockaddr *myaddr,
socklen_t addrlen);
9. •Servers bind to their well-known port when they
start.
•A process can bind a specific IP address to its socket.
•A client does not bind an IP address to its socket .
10. • EACCES The address is protected.
• EADDRINUSE The given address is already in use.
• EBADF The sockfd is not a valid descriptor.
• EINVAL The socket is already bound to an address.
11. The listen function is called only by a TCP server and it performs two
actions:
• Converts an unconnected (active) socket into a passive socket.
• Specifies the maximum number of connections .
#include <sys/socket.h>
int listen(int sockfd, int
backlog);
12. • Called after both the socket and bind function .
• Backlog - for a given listening socket, the kernel maintains 2
queues:
• An incomplete connection queue - Contains an entry for each
SYN that has arrived from a client .
• A completed connection queue, entry for each client with whom
3-way handshake has completed.
13.
14. • Accept is called by a TCP server
#include <sys/socket.h>
int accept(int sockfd, struct sockaddr
*cliaddr, socklen_t *addrlen);
• The cliaddr and addrlen args are used to return
the protocol address .
15. • Fork() function is the only way in Unix to create a new process
#include <unistd.h>
pid_t fork(void);
• Called once but returnsTWICE
• Once in the parent process (returns child process id),
• and once in the child process (return of 0)
16. • Used for multitasking .
• The process want to handle another program .
17.
18. • Used when multiple clients are accessing a single
server .
• fork() is used in such cases to handle each client.
19. • Used to close a socket and terminate a TCP
connection
#include <unistd.h>
int close(int sockfd);
• Socket descriptor is no longer usable to the app
process.