This repo serves as an introductory repo to showcase how to do basic programming using TCP protocol. Relevant documents and knowledge will be shared in this readme.
Socket programming is a way of connecting two nodes on a network to communicat with each other. One socket(node) listens on a particular port and IP while the other reaches out to form a connection. Refer to diagram below:-
As shown above, it is a connection between two nodes where one listens and one talks. The listener is generally called the server node while the talker is the client node.
As shown above, there are mainly two similar processes that is done to create a TCP connection; Server Process and Client Process. We will focus on each component separately.
socket()
The socket() function creates the socket for the server. The function is declared as follows:-
int sockfd = socket(domain, type, protocol)`- sockfd: Socket file descriptor
- domain: Specifies communication domain. For the same host but different processes, use
AF_LOCAL. For different hosts, useAF_INETfor hosts connected by IPV4 andAF_INET6for hosts connected by IPV6. - type: Specifies communication type.
SOCK_STREAMis used for TCP(connection-oriented).SOCK_DGRAMis used for UDP(connectionless). - protocol: Protocol value for Internet Protocol (IP), which is 0.
bind()
The bind() function binds the socket to the address and port number specified. The function is declared as follows:-
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);- sockfd: Socket file descriptor created previously
- addr: pointer to the memory location of the socket address
- addrlen: Size of the socket
listen()
The listen() function puts the server socket into passive mode where it waits for the client to approach the server to make a connection. The function is declared as follows:-
int listen(int sockfd, int backlog);- backlog: Is the maximum length to which the queue of pending connections for sockfd to grow.
accept()
The accept() function will extract the first connection request on the queue of pending connections for the listening socket and return a file descriptor referring to that socket.
int new_socket=accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);- sockfd: The file descriptor for the new connected socket
- addr: Address for the new connected socket
- addrlen: Address length for the new connected socket
socket()
This function is exactly the same as the server process function.
connect()
The connect() function connects the socket referred to by the file descriptor to the address specified by addr. The function is declared as follow:-
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
