We'll learn about network programming today. As a core concept of Networks, it goes deep and requires a good amount of time to cover. We'll try to limit it to the scope of specialist officer's exams. If anyone interested in deep learning, raise it in comments, I'll share the sources.
==>> This article is a part of PK Series
What is Inter Process Communication (IPC)?
What is a file descriptor?
What is a socket?
Types of Sockets
- SOCK_STREAM: Stream sockets, which provide reliable two way connection oriented communication streams. It uses TCP.
- SOCK_DGRAM: Datagram sockets, which provide connectionless, unreliable service, used for packet by packet transfer of information. It uses User Datagram Protocol (UDP)
System Calls using Sockets
1. socket( ) - returns socket descriptor, -1 on error.Syntax:
#include <sys/types.h>
#include <sys/socket.h>
int socket (int domain, int type, int protocol);
domain should be set to AF_INET (uses ip address)
type - SOCK_STREAM or SOCK_DGRAM
protocol- set to zero typically.
2. bind( ) - associates the socket with an address, -1 on error.
Syntax:
#include <sys/types.h>
#include <sys/socket.h>
int socket (int sockfd, struct sockaddr *my_addr, int addrlen);
sockfd- socket file descriptor returned by socket( ).
my_addr- pointer to a structure that contains information about local IP address and port number.
addrlen- set to sizeof (struct sockaddr)
3. connect( ) - connect to a remote socket, -1 on error
Syntax:
#include <sys/types.h>
#include <sys/socket.h>
int socket (int sockfd, struct sockaddr *serv_addr, int addrlen);
serv_addr- pointer to a structure that contains the destination IP address and port number
4. listen( ) - wait for incoming connections, -1 on error
Syntax:
int listen (int sockfd, int backlog);
backlog- set max no of requests that will be queued before requests are denied.
5. accept( )- returns a new socket file descriptor for every single connection, -1 on error
Syntax:
#include <sys/socket.h>
int accept (int sockfd, void *addr, int *addrlen);
addr- pointer to a local structure sockaddr_in, here information about incoming connection will be stored
addrlen- should be set to sizeof(struct sockaddr_in) before accept( ) is called.
Other systems calls along with rest of the topic will be covered in next article.
Quote of the day
Join 40,000+ readers and get free notes in your email
This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at http://ift.tt/jcXqJW.
No comments:
Post a Comment