0% found this document useful (0 votes)
36 views

Socket Programming

The document discusses socket programming and networking concepts. It explains what sockets are and key system calls used in socket programming like socket(), bind(), listen(), accept(), connect(). It describes how these calls work for both connection-oriented and connectionless protocols and the parameters used. It also covers related topics like byte ordering and address conversion.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Socket Programming

The document discusses socket programming and networking concepts. It explains what sockets are and key system calls used in socket programming like socket(), bind(), listen(), accept(), connect(). It describes how these calls work for both connection-oriented and connectionless protocols and the parameters used. It also covers related topics like byte ordering and address conversion.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

INTRODUCTION TO SOCKET

PROGRAMMING
WHAT IS COMPUTER NETWORKS?
 Computer network is a communication network in which a collection of
computers are connected together to facilitate data exchange
 The connection between the computers can be wired or wireless.
 A computer network basically comprises of 5 components:
 Sender
 Receiver
 Message
 Transmission medium
 Protocols

Fig 1: Components of data communication


CLIENT SERVER MODEL

Fig 2: Client Server model

Fig 3: Communication in Client Server model


AN ANALOGY
SOCKET PROGRAMMING IN
UNIX
Socket Address = IP Address +
What is “socket”? Port Number
• A socket is a MECHANISM TO PROVIDE SERVICES to the
application program.

• Using a socket, two processes can communicate with each other

• A socket is bi-directional (full-duplex) transmission

• A socket can be created dynamically.(created any time)

• In operating systems, a socket is a structure(does not have methods)

• A socket address is the combination of an IP address and a port number


SOCKET SYSTEM CALLS FOR
CONNECTION-ORIENTED PROTOCOL
SOCKET SYSTEM CALLS FOR
CONNECTION-LESS PROTOCOL
• The server begins by carrying out a passive open as follows.
(Server when it starts, opens the door for incoming requests but
never initiates a service until it is requested to do so. This is called
passive open.)

• The socket call creates a TCP socket.

• The bind call then binds the well-known port number of the
server to the socket.

• The listen call turns the socket into a listening socket that can
accept incoming connections from clients.

• The accept call puts the server process to sleep until the arrival
of a client connection.
• The client does an active open(A client opens the communications
channel using the IP address of the remote host and the well-
known port address of the specific server program running on that
machine).

• The socket call creates a socket on the client side, and the connect
call establishes the TCP connection to the server with the specified
destination socket address.

• The accept function at the server wakes up and returns the


descriptor for the given connection namely, the source IP address,
source port number, destination IP address, and destination port
number.

• The client and server are now ready to exchange information.


ELEMENTARY SOCKET
SYSTEM CALLS
Socket facilities are provided to programmers through
system calls except that control is transferred to the OS
kernel once the call is invoked.

To use these facilities, the header files<sys/types.h> and


<sys/socket.h>

Before an application program can transfer any data it


must first create an endpoint for communication by
calling socket
BERKELEY SOCKETS

• socklen_t and size_t are same as int


• u_long and uint32_t are same as long int
• u_short and uint16_t are same as short
“SOCKET” SYSTEM CALL
DEFINITION AND PARAMETERS

• To do network I/O, the first thing a process must do is


create a socket by calling the socket system call,
specifying the type of communication protocol desired
(TCP, UDP etc.) as follows
int socket(int family, int type, int protocol);

• This system call returns an integer which is (similar to file


descriptor) a reference to the socket called the socket
descriptor. On error, -1 is returned.
• Since we are interested in internet protocols the family
parameter is set to AF_INET.

• The type field takes the values SOCK_STREAM which means


a stream socket is created (used in the case of TCP) and
SOCK_DGRAM which means a datagram socket is created
(used in the case of UDP).

• The protocol argument to the socket system call is typically set


to 0 to indicate default protocol.

• The default protocol for SOCK_STREAM with AF_INET


family is TCP.
Example
if ( (sd = socket( AF_INET, SOCK_STREAM, 0 )) < 0 ) {
cout<<“Socket creation error”;
exit(-1);
}
 SOCK_RAW – provides access to internal network interfaces
and is available only to super-user.

 SOCK_SEQPACKET – Provides a sequenced, reliable, two-way


connection-based data transmission path for datagrams of fixed
maximum length
“BIND” SYSTEM CALL
WHY USE BIND?
• Bind helps the servers to register themselves with the system.
It tells the system that “any messages received at the particular
IP address and the specified port be directed to me”.

• This is required in case of both connection-oriented (like TCP)


and connectionless (like UDP) servers.

• A connectionless client needs to assure that the system assigns


it some unique address, so that the other end (the server) has a
valid return address to send its responses to. This is not
required in the case of connection-oriented client.
“BIND” SYSTEM CALL
DEFINITION AND PARAMETERS
• This system call assigns a name to an unnamed socket –
int bind(int sockfd, struct sockaddr *myaddr, socklen_t
addrlen);
• The sockfd argument is nothing but the socket descriptor which
is obtained after executing the socket system call.

• The second argument is a pointer to a protocol-specific address


and the third argument is the size of the address structure
passed as reference in the second argument.

• Since we are interested in Internet Protocols the second


argument passed is of type sockaddr_in.
“BIND” SYSTEM CALL
THE SOCKADDR_IN STRUCTURE
• The structure sockaddr_in (defined in <netinet/in.h>) is as
follows –
struct in_addr {
u_long s_addr; struct sockaddr {
unsigned short sa_family;
};
char sa_data[14];
struct sockaddr_in { };
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8]; /* unused */
};
“BIND” SYSTEM CALL
MORE ON SOCKADDR_IN STRUCTURE…

• The sin_family field takes the value AF_INET indicating that an


internet family protocol is being used.

• The sin_port field identifies the server/client application to the host


where it is running.

• The sin_addr structure has only one field s_addr which identifies the
server side IP address (32-bits) to which various clients can connect.

• The sin_port and sin_addr fields are network byte ordered i.e., a
format that is permissible for a given network protocol.
 Consider a 16-bit integer that is made up of 2 bytes. There are
two ways to store the two bytes in memory: with the low-
order byte at the starting address, known as little-endian byte
order, or with the high-order byte at the starting address,
known as big-endian byte order.
 So that machines with different byte order conventions can
communicate, the Internet protocols specify a canonical byte
order convention for data transmitted over the network. This
is known as network byte order or big endian byte order.
BIG-ENDIAN BYTE ORDER IS
ALSO REFERRED TO LITTLE-ENDIAN BYTE
AS NETWORK BYTE ORDER ORDER IS ALSO
REFERRED TO
AS HOST BYTE ORDER
“BIND” SYSTEM CALL
BYTE ORDERING ROUTINES
• The various byte ordering routines that provide the
necessary conversion from host byte ordering to network
byte ordering and vice versa are as follows –
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
• htonl and ntohl convert from host-to-network and network-
to-host byte order respectively and return a long integer
value representing the converted ordering.
“BIND” SYSTEM CALL
MORE ON BYTE ORDERING ROUTINES…
• htons and ntohs convert from host-to-network and
network-to-host byte order respectively and return a short
integer value representing the converted ordering.
• htonl and ntohl can be used while converting network IP
addresses which are passed to sin_addr.s_addr field of
the sockaddr_in structure.
• htons and ntohs can be used while converting the 16-bit
port number that is passed to the sin_port field of the
sockaddr_in structure.
“BIND” SYSTEM CALL
ADDRESS CONVERSION ROUTINES
• An internet address is usually written in dotted-decimal
notation i.e., in the form of A.B.C.D. Thus it is necessary
that this address be converted into proper format before
passing the value to the sin_addr.s_addr field of the
sockaddr_in structure.
• The following functions provide the necessary address
conversion –
in_addr_t inet_addr(const char *cp);
char *inet_ntoa(struct in_addr in);
• The inet_addr function converts the dotted-decimal
address string into binary data in network byte order.
“BIND” SYSTEM CALL
MORE ON ADDRESS CONVERSION ROUTINES…

• If the input provided to inet_addr is invalid an error


occurs, which makes the function returns an address value
where all the 32 bits are set to 1, which means
255.255.255.255 is returned if an error occurs.
• Thus for the inet_addr function 255.255.255.255 is
considered to be an error, but nevertheless it is a valid
network (reserved) address. Thus the inet_addr function
fails in this regard. (A solution to this discussed shortly).
• The inet_ntoa function does the reverse conversion i.e., it
extracts the 32-bit internet address and converts it into the
usual dotted-decimal notation in host byte order.
“BIND” SYSTEM CALL
MORE ON ADDRESS CONVERSION ROUTINES…

• The inet_addr function is an obsolete interface to


inet_aton which provides a clearer way to indicate errors.
The function prototype is as follows –
int inet_aton(const char *cp, struct in_addr *inp);
• inet_aton converts the internet host address cp from the
usual dotted-decimal notation into binary data and stores
the converted address in the structure pointed to by inp.
• inet_aton returns a non-zero value if the address provided
is valid or else zero is returned, thus solving the problem
posed by inet_addr. Thus it is advised that inet_aton be
used instead of inet_addr.
“BIND” SYSTEM CALL
SOME MORE INFORMATION…
• Since the second argument to the bind system call is of
type pointer to sockaddr structure, but the network
specific address structure sockaddr_in is used, this
(sockaddr_in) structure has to be type-casted before
passing its address to bind. Even though no errors are
raised (a warning will be given though) the call fails.
• On success, 0 is returned. On error, -1 is returned by the
bind system call.
“LISTEN” SYSTEM CALL
DEFINITION AND PARAMETERS

• This system call is used by a connection-oriented server


(i.e., SOCK_STREAM socket) to indicate that it is
willing to receive connections from clients.
• The function prototype is as follows –
int listen(int sockfd, int backlog);
• The sockfd field is nothing but the socket descriptor
obtained after executing the socket system call.
• The backlog parameter defines the maximum length of
the queue of pending connections may grow to. This
argument is usually specified as 5 which the maximum
value currently allowed.
“ACCEPT” SYSTEM CALL
DEFINITION AND PARAMETERS
• The accept system call extracts the first connection
request on the queue of pending connections and creates a
new connected socket with mostly the same properties as
that of sockfd. This newly created socket’s descriptor is
returned and only this descriptor must be used for further
communication with the intended client. The original
socket descriptor sockfd remains unaffected by this call.
• The function prototype is as follows –
int accept(int sockfd, struct sockaddr *peer,
socklen_t *addrlen);
“ACCEPT” SYSTEM CALL
SOCKFD, PEER AND ADDRLEN PARAMETERS…
• The sockfd parameter is the socket descriptor that was
created with socket, bound to a local address with bind
and is listening for connections after listen.
• The argument peer is a pointer to a sockaddr structure.
This structure will be filled in with the address of the peer
entity (connecting entity or client). Since the
sockaddr_in structure is used (in the case of internet
family protocols) the structure passed as the second
argument to accept must be adequately type-casted.
• The addrlen is a value-result parameter whose value is
initially set to contain the size of the structure pointed to
by peer.
“ACCEPT” SYSTEM CALL
PARAMETERS AND MORE…
• On return the value in the addrlen parameter is updated
so as to contain the actual length (in bytes) of the address
returned.
• accept system call blocks the caller until a connection
from a client is established.
• As mentioned earlier accept returns a non-negative
integer that represents the descriptor for the accepted
socket while listen returns 0 on success.
• Both listen and accept system calls return -1 if any error
occurs.
“CONNECT” SYSTEM CALL
DEFINITION AND PARAMETERS
• A client process can establish a connection with a server
using the connect system call as follows –
int connect(int sockfd, const struct sockaddr
*servaddr, socklen_t addrlen);
• The sockfd parameter is the socket descriptor that is
returned by the socket system call (at the client side).
• The servaddr parameter is the address of the server (IP
address and port number of the server) to which the client
wishes to connect.
• addrlen is the length of the address structure pointed to
by servaddr.
“CONNECT” SYSTEM CALL
CONNECTION-ORIENTED VS. CONNECTIONLESS…
• For connection-oriented protocols the connect system call
results in the actual establishment of a connection between
the client and the server.
• Specific parameters such as buffer size, amount of data to
exchange between acknowledgements etc. might be agreed
upon in the process of establishing the connection.
• A connectionless client can also use the connect system call.
But here an actual establishment of connection between the
server and client does not take place.
• In the case of a connectionless client, the servaddr is stored
by the process in the local system so that all future data is
directed to the address specified by servaddr.
“CONNECT” SYSTEM CALL
CONNECTION-ORIENTED VS. CONNECTIONLESS…

• And the client socket will receive only datagrams from


the address specified by servaddr (in the case of a
connectionless client).
• Thus if the connectionless client wishes to receive
datagrams from another host then the only thing that
needs to be done is change the address in the servaddr
address structure and use connect again.
• The advantage of using connect with a connectionless
client is that every time a datagram needs to be sent, the
destination address need not be specified again and again
(specially if there is large amount of data to be
exchanged).
“CONNECT” SYSTEM CALL
SOME MORE INFORMATION…
• If the connection or binding succeeds, 0 is returned. On
error, -1 is returned.
• Note that all the system calls discussed so far under
Berkeley Sockets can be used by including the following
headers –
<sys/types.h>
<sys/socket.h>
• To use the system calls send, sendto, recv and recvfrom
(discussed next) the above mentioned header files must be
included in the socket program.
“SEND” SYSTEM CALL
DEFINITION AND PARAMETERS
• A connection-oriented client/server can use the send
system call to exchange messages between each other.
The function prototype is as follows –
int send(int sockfd, const void *msg, size_t len, int
flags);
• sockfd is the socket descriptor returned by the socket
system call in the case of the client and the new socket
descriptor returned by the accept system call in the case
of the server.
• msg is pointer to the message that has to be read or
written and len is the number of bytes has to be read or
written .
• The flags parameter is usually set to 0.
“RECV” SYSTEM CALL
DEFINITION AND PARAMETERS
• To receive messages from a connected socket a
client/server can use the recv system call as follows –
int recv(int sockfd, void *buf, size_t len, int
flags);
• sockfd and flags have the same meaning as in the send
system call.
• Here buf is nothing but the message that will be received
by the client/server.
• The len parameter specifies the number of characters (in
bytes) that can be read at once.
• The recv system call blocks until a message is received.
“CLOSE” SYSTEM CALL
DEFINITION AND PARAMETERS
• The Unix close system call is also used to close a socket.
• The function prototype is as follows –
int close(int fd);
• Here fd refers to the socket descriptor.
• The close system call does not close the socket at once.
Before closing it tries to send any queued data or any
queued data to be sent is flushed.
• The close system call returns 0 on success and -1 on
error.
SENDTO()--UDP SOCKETS
 int sendto(int socket, char *buffer, int length, int
flags, struct sockaddr
*destination_address, int
address_size);
 For example:
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(12345);
sin.sin_addr.s_addr = inet_addr("128.227.22.43");
char *msg = "Hello, World";
sendto(s, msg, strlen(msg)+1, 0, (struct sockaddr *)sin, sizeof(sin));
RECVFROM()--UDP SOCKETS
 Int recvfrom(int socket, char *buffer, int length,
int flags, struct sockaddr *sender_address, int
*address_size)

 For example:
struct sockaddr_in sin;
char msg[10000];
int ret;
int sin_length;
sin_length = sizeof(sin);
ret = recvfrom(s, msg, 10000, 0, (struct sockaddr *)sin,
&sin_length);
printf("%d bytes received from %s (port %d)\n", ret,
inet_ntoa(sin.sin_addr), sin.sin_port);
A Simple TCP server program

#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>

#define MAXSIZE 50
main()
{
int sockfd,newsockfd,retval;
socklen_t actuallen;
int recedbytes,sentbytes;
struct sockaddr_in serveraddr,clientaddr;
char buff[MAXSIZE];
int a=0;

sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1) {
cout<<"\nSocket creation error";
exit(-1); }
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(3387);
serveraddr.sin_addr.s_addr=htonl(INADDR_ANY);

/*With IPv4, the wildcard address is specified by the constant INADDR_ANY, whose
value is normally 0. This tells the kernel to choose the IP address .*/

retval=bind(sockfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));
if(retval==-1) {
cout<<"Binding error"; close(sockfd);
exit(0); }

retval=listen(sockfd,1);
if(retval==-1) { close(sockfd);
exit(0); }
actuallen=sizeof(clientaddr);
newsockfd=accept(sockfd,(struct sockaddr*)&clientaddr,&actuallen);
if(newsockfd==-1) {
close(sockfd);
exit(0); }

recedbytes=recv(newsockfd,buff,sizeof(buff),0);
if(recedbytes==-1) {
close(sockfd);
close(newsockfd);
exit(0); }

puts(buff);
cout<<"\n";
gets(buff);
sentbytes=send(newsockfd,buff,sizeof(buff),0);
if(sentbytes==-1) {
close(sockfd);
close(newsockfd);
exit(0);
}

close(newsockfd);
close(sockfd);
}
Header Functions defined
arpa/inet.h inet functions: inet_aton,
inet_ntoa, and inet_addr
unistd.h System call: close, fork, exec
sys/socket.h basic socket definitions
recv, send
sys/types.h basic system data types
netinet/in.h sockaddr_in{} and other
Internet definitions
sys/stat.h for S_xxx file mode constants
fcntl.h for nonblocking

You might also like