Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
55 views20 pages

Exno2 Introduction To Socket Programming Aim: To Study About The Basics of Socket in Network Programming

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 20

EX NO 2

INTRODUCTION TO SOCKET PROGRAMMING

Aim:
To study about the basics of Socket in Network Programming
Network Programming
Network programming involves writing programs that communicate with other programs
across a computer N/W. One program is normally called the client, and the other the server.
Common examples in the TCP/IP are web clients (browsers) & Web Servers, FTP clients &
server and Telnet clients & servers.
To facilitate communication between unrelated processes, and to standardize network
programming, an API is needed. There are two such APIs:
1. Sockets, sometimes called Berkeley Sockets
2. XTI (X/open transport interface)
Socket
In TCP/IP, an addressable point that consists of an IP address and a TCP or UDP port
member that provides application with access to TCP/IP protocol is called Socket.
A socket is an abstraction that represents an endpoint of communication. The operations
that can be performed on a socket include control operations (such as associating a port number
with the socket, initiating or accepting a connection on the socket, or destroying the socket), data
transfer operations (such as writing data through the socket to some other application, or reading
data from some other application through the socket) and status operations (such as finding the
IP address associated with the socket). The complete set of operations that can be performed on a
socket constitutes the Sockets API (Application Programming Interface).
Structures
Structures are used in socket programming to hold information about the address. The
generic socket address structure is defined below:
struct sockaddr
{
unsigned short sa_family;
/* address family */
char sa_data[14];
/* 14 bytes of protocol address*/
};

IPv4 Socket Address Structure


This structure is also called as Internet socket address structure. It is defined by
including the <netinet/in.h> header.
struct in_addr {
in_addr_t
s_addr;
/* 32-bit IPv4 address, network byte ordered */
};
struct sockaddr_in{
unit_t sin_len;
/* length of structure (16 byte) */
sa_family_t sin_family; /*AF_INET*/
in_port_t
sin_port;
/* 16-bit TCP or UDP port number */
/* network byte ordered */
struct in_addr sin_addr;
/*32-bit Ipv4 address, network byte ordered */
char
sin_zero[8]; /* unused initialize to all zeroes */
};
Important functions
1.socket()
This function is called by both TCP server and client process to create an empty socket.
#include <sys/socket.h>
int socket (int family, int type, int protocol);
family: specifies the protocol family and is one of the constants below:
Family

Description

AF_INET

IPv4 protocols

AF_INET6

IPv6 protocols

AF_LOCAL

Unix domain protocols

AF_ROUTE

Routing sockets

AF_KEY

Key sockets

type: indicates communications semantics


SOCK_STREAM - stream socket
SOCK_DGRAM - datagram socket
SOCK_RAW - raw socket
protocol: set to 0 except for raw sockets.
Returns on success: socket descriptor (a small nonnegative integer), on error: -1
2. bind()

The bind function assigns a local protocol address to a socket. The protocol address is the
combination of either a 32-bit IPV4 address or a 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);
sockfd: a socket descriptor returned by the socket function.
*myaddr: a pointer to a protocol-specific address.
addrlen: the size of the socket address structure.
Returns on success: 0, on error: -1
3. connect()
The connect function is used by a TCP client to establish a connection with a TCP server.
#include <sys/socket.h>
int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen);
sockfd: a socket descriptor returned by the socket function
*servaddr: a pointer to a socket address structure
addrlen: the size of the socket address structure
Returns on success: 0, on error: -1
4. listen()
The listen function is called only by a TCP server to converts an unconnected socket into a
passive socket, indicating that kernel should accept incoming connection requests directed to its
socket.
#include<sys/socket.h>
int listen (int sockfd, int backlog);
sockfd: a socket descriptor returned by the socket function.
backlog: maximum number of connections that the kernel should queue for this socket.
Returns on success: 0, on error: -1
5. accept()
The accept function is called by the TCP server to return the next completed connection from the
front of the completed connection queue.
#include<sys/socket.h>
int accept (int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);
sockfd: This is the same socket descriptor as in listen call.
*cliaddr: used to return the protocol address of the connected peer process
*addrlen: length of the address.
Returns on success: a new (connected)socket descriptor, on error:-1

6. close()
The close function is used to close a socket and terminate a TCP connection.
#include <unistd.h>
int close (int sockfd);
sockfd: This socket descriptor is no longer useable.
Returns on success: 0, on error: -1
7. read()
The read function is used to receive data from the specified socket.
#include <unistd.h>
ssize_t read(int sockfd, const void * buf, size_t nbytes);
sockfd: a socket descriptor returned by the socket function.
buf: buffer to store the data.
nbytes: size of the buffer
Returns: number of bytes read if OK,0 on EOF, -1 on error
8. write()
The write function is used to send the data through the specified socket.
#include <unistd.h>
ssize_t write(int sockfd, const void * buf, size_t nbytes);
sockfd: a socket descriptor returned by the socket function.
buf: buffer to store the data.
nbytes: size of the buffer
Returns: number of bytes written if OK,0 on EOF, -1 on error
9. sendto()
This function is similar to the write function, but additional arguments are required.
#include<sys/socket.h>
ssize_t sendto(int sockfd, const void *buff, size_t nbyte, int flag,
const struct sockaddr *to, socklen_t addrlen);
sockfd socket descriptor
*buff pointer to buffer to write from.
nbytes number of bytes to write.
to socket address structure containing the protocol address of where the data is to be sent.
addrlen size of the socket address structure
Returns: number of bytes read or written if OK,-1 on error
10. recvfrom()
This function is similar to the read function, but additional arguments are required.

#include<sys/socket.h>
ssize_t recvfrom(int sockfd, void *buff, size_t nbyte, int flag,
struct sockaddr *from, socklen_t *addrlen);
sockfd socket descriptor
*buff pointer to buffer to read.
nbytes number of bytes to read.
addrlen size of the socket address structure
from - socket address structure of who sent the datagram.
Returns: number of bytes read or written if OK,-1 on error

Socket functions for connection-oriented communication


TCP Server
socket()

bind()

listen()

accept()

TCP Client
socket()

blocks until connection from client


Connection establishment

conect()
data ( request)
write()

read()

read()

process request
data ( reply)
write()

close()

EOF notification
read()

close()

Socket functions for connection-less communication


UDP Server
socket()

bind()
UDP Client
socket()

sendto()

recvfrom()

Blocks until datagram received from a client


Data (request)

Process request
Data (reply)
recvfrom()

close()

sendto()

Program to create a socket


/* Ex-1
#include <stdio.h>

Program To Create a Socket

*/

/* NEEDED HEADER FILES */

#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
int main()
{
int sockfd1,sockfd2;

/* sokcet file descriptors */

sockfd1=socket(AF_INET,SOCK_STREAM,0); /* socket system call */


sockfd2=socket(PF_INET,SOCK_DGRAM,0);

if(sockfd1==-1)

/* error checking */

{
printf("Socket1 not Created\n");
}
else
{
printf("Socket1 Created and \t Socket1 File Descriptor value is %d \n",sockfd1);

if(sockfd2==-1)
{
printf("socket2 creation error");
}
else
{
printf("Socket2 created and \t socket2 descriptor value is %d\n",sockfd2);
}
}}

Output:
Socket 1 file description value is 3
Socket 4 file description value is 4

Program to Bind a socket


/* Ex-2 Program to Bind a Socket */
#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#define PORTNO 2000
int main()
{

/* Type definition of a Port number */

int sockfd,i=PORTNO;
struct sockaddr_in myaddr;

/* Builtin structure for internet address */

if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{printf("Socket Creation Error\n");}

myaddr.sin_family=AF_INET;

/* Structure variable definition */

myaddr.sin_port=htons(PORTNO);
myaddr.sin_addr.s_addr=INADDR_ANY;
memset(&(myaddr.sin_zero),'\0',8); /* fills with constant byte to remaining space */

/* socket Binding process and error checking */


if(bind(sockfd,(struct sockaddr *)&myaddr,sizeof(struct sockaddr))!=-1)
{
printf(" Socket is Binded at port %d\n",i);
}
else
{
printf("Binding Error\n");
}
}

OUTPUT:
SOCKET IS BINDED AT PORT 2000

Program to implement listen() system call

/* Ex-3 Program to implement LISTEN system call */

#include <stdio.h>
#include <sys/types.h>

/* These are the usual header files */

#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 3550 /*Assigning Port number */


#define BACKLOG 12 /* Number of allowed connections */

main()
{

int fd;

/* file descriptors */

struct sockaddr_in server;

/* server's address information */

struct sockaddr_in client;

/* client's address information */

int sin_size;
int x;
if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ){ /* calls socket() */
printf("socket() error\n");
exit(-1);
}
server.sin_family = AF_INET;
server.sin_port = htons(PORT);

/* Remember htons() from "Conversions" section? =) */

server.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY puts your IP address


automatically */
bzero(&(server.sin_zero),8);

/* zero the rest of the structure */

if(bind(fd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1) /* calls bind() */


{

printf("bind() error\n");
exit(-1);

x=listen(fd,BACKLOG) ;

/* calls listen() */

if(x==-1)
{
printf("listen() error\n");
exit(-1);
}
else
{
printf(Server is in listening mode \n );
}
close(fd);
}

/* close fd */

OUTPUT:
Server is in listening mode.

Program for accept() system call

/* Ex-3 Program to implement ACCEPT system calls */

#include <stdio.h>

/* These are the usual header files */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 3550 /* Assigning Port numbers */


#define BACKLOG 2 /* Number of allowed connections */
main()
{

int fd, fd2;

/* file descriptors */

struct sockaddr_in server;

/* server's address information */

struct sockaddr_in client;

/* client's address information */

int sin_size;
if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ) /* calls socket() */
{
printf("socket() error\n");
exit(-1);

server.sin_family = AF_INET;
server.sin_port = htons(PORT);

/* Remember htons() from "Conversions" section */

server.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY puts your IP address


automatically */
bzero(&(server.sin_zero),8);

/* zero the rest of the structure */

if(bind(fd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1){ /* calls bind() */


printf("bind() error\n");
exit(-1);
}

if(listen(fd,BACKLOG) == -1)
{
printf("listen() error\n");
exit(-1);
}
printf("server is in accept mode \n ");

while(1)

/* calls listen() */

{
sin_size=sizeof(struct sockaddr_in);
if ((fd2 = accept(fd,(struct sockaddr *)&client,&sin_size))==-1){ /* calls accept() */
printf("accept() error\n");
exit(-1);
}
else
printf(" Server is in accept mode ");
printf("You got a connection from %s\n",inet_ntoa(client.sin_addr) ); /* prints client's IP */

close(fd2); /* close fd2 */


}
}

OUTPUT:
cc.vjkumar
./a.out
Bind()error
Result:
Thus the basics of socket with example peograms are studied.

You might also like