Socket Programming
#1

Definition

Sockets are interfaces that can "plug into" each other over a network. Once so "plugged in", the programs so connected communicate. A "server" program is exposed via a socket connected to a certain /etc/services port number. A "client" program can then connect its own socket to the server's socket, at which time the client program's writes to the socket are read as stdin to the server program, and stdout from the server program are read from the client's socket reads.

Before a user process can perform I/O operations, it calls Open to specify and obtain permissions for the file or device to be used. Once an object has been opened, the user process makes one or more calls to Read or Write data. Read reads data from the object and transfers it to the user process, while Write transfers data from the user process to the object. After all transfer operations are complete, the user process calls Close to inform the operating system that it has finished using that object.

When facilities for InterProcess Communication (IPC) and networking were added, the idea was to make the interface to IPC similar to that of file I/O. In Unix, a process has a set of I/O descriptors that one reads from and writes to. These descriptors may refer to files, devices, or communication channels (sockets). The lifetime of a descriptor is made up of three phases: creation (open socket), reading and writing (receive and send to socket), and destruction (close socket).

History
Sockets are used nearly everywhere, but are one of the most severely misunderstood technologies around. This is a 10,000 foot overview of sockets. It's not really a tutorial - you'll still have work to do in getting things working. It doesn't cover the fine points (and there are a lot of them), but I hope it will give you enough background to begin using them decently.I'm only going to talk about INET sockets, but they account for at least 99% of the sockets in use. And I'll only talk about STREAM sockets - unless you really know what you're doing (in which case this HOWTO isn't for you!), you'll get better behavior and performance from a STREAM socket than anything else. I will try to clear up the mystery of what a socket is, as well as some hints on how to work with blocking and non-blocking sockets. But I'll start by talking about blocking sockets. You'll need to know how they work before dealing with non-blocking sockets.

Part of the trouble with understanding these things is that "socket" can mean a number of subtly different things, depending on context. So first, let's make a distinction between a "client" socket - an endpoint of a conversation, and a "server" socket, which is more like a switchboard operator. The client application (your browser, for example) uses "client" sockets exclusively; the web server it's talking to uses both "server" sockets and "client" sockets.
Of the various forms of IPC (Inter Process Communication), sockets are by far the most popular. On any given platform, there are likely to be other forms of IPC that are faster, but for cross-platform communication, sockets are about the only game in town.

They were invented in Berkeley as part of the BSD flavor of Unix. They spread like wildfire with the Internet. With good reason -- the combination of sockets with INET makes talking to arbitrary machines around the world unbelievably easy (at least compared to other schemes).
Reply
#2


[attachment=8289]

By Rupam Adhikary
B.Tech 5th sem. Don bosco college of engg & tech.Assam



HEADER FILES

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include<unistd.h>
#include<crypt.h>

SERVER PROGRAM
//main function
int sock,i=0,j=0;
int addr_len, bytes_read,n,fl=0;
FILE *fp;
char *temp,*pass;
char c1[1024],c2[1024],c3[1024],c4[1024],c5[1024];
char recv_data[1024],send_data[1024];
struct sockaddr_in server_addr , client_addr;
struct sockaddr_in array[20];

if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("Socket");
exit(1);
}


server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5004);
server_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_addr.sin_zero),8);

if (bind(sock,(struct sockaddr *)&server_addr,
sizeof(struct sockaddr)) == -1)
{
perror("Bind");
exit(1);
}

addr_len = sizeof(struct sockaddr);



while(1)

//receiving connecting message
bytes_read = recvfrom(sock,recv_data,1024,0,(struct sockaddr *)&client_addr, &addr_len);
recv_data[bytes_read] = '\0';
//displaying Connecting message
printf("\n(%s , %d) said : ",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
printf("%s\n", recv_data);
fflush(stdout);
//receving user name
bytes_read = recvfrom(sock,recv_data,1024,0,(struct sockaddr *)&client_addr, &addr_len);

recv_data[bytes_read] = '\0';
printf("\nThe user name is:%s\n",recv_data);
fflush(stdout);
strcpy(c4,recv_data);

//Acquiring encrypted password for corresponding user
fp=fopen("/etc/shadow","r");
if(!fp)
{
printf("Can't open Shadow file\n");
fflush(stdout);
}
while(!feof(fp))
{
i=0;
fgets(c1,1024,fp);
while(c1[i]!=':')
{
c2[i]=c1[i];
i++;
}
c2[i]='\0';
if(strcmp(c2,c4)==0)
{
fl=0;
n=i;
break;
}
}//end of while(!feof(fp))


i++;
while(c1[i]!=':')
{
c5[j]=c1[i];
j++;
i++;
}
c5[j]='\0';
printf("Acquiring the ENCRYPTED PASSWORD for the user %s.......\n",recv_data);
printf("Encrypted Password acquired for the user %s and the Password is",recv_data);
printf("\n%s\n",c5);

//receving password
bytes_read = recvfrom(sock,recv_data,1024,0,(struct sockaddr *)&client_addr, &addr_len);
recv_data[bytes_read] = '\0';
printf("\nThe password entered by the Client is:%s\n",recv_data);
fflush(stdout);
strcpy(pass,recv_data);



//encrypting the received passwords
temp=crypt(pass,c5);
printf("Encrypting the Entered Password.........\n");
printf("Password Encrypted and the password is:");
printf("%s\n",temp);
//comparing the passwords
if(strcmp(temp,c5)==0)
{
printf("Access Granted\n");
strcpy(send_data,"GRANTED");
sendto(sock,send_data,strlen(send_data),0,(struct sockaddr *)&client_addr,sizeof(struct sockaddr));
}
else
{
printf("Access Denied\n");
strcpy(send_data,"DENIED");
sendto(sock,send_data,strlen(send_data),0,(struct sockaddr *)&client_addr,sizeof(struct sockaddr));
}
//end of while(1)
fclose(fp);
return 0;//end of main server program








Reply
#3
Presented By :
Divya Sharma

[attachment=12329]
What are Sockets ?
• A socket is defined as an endpoint of communication
• Service access point of TCP/IP protocol stack

• between Application layer and Transport layer
• A file descriptor that lets an application read/write data from/to the network
• Once configured the application can

• Send data to the socket
• Receive data from the socket
network
int fd; /*socket descriptor*/
if ((fd = socket(AF_INET, SOCK-STREAM, 0)) < 0) }
fd = socket(AF_INET,
SOCK_STREAM, 0)) < 0) }
perror(“socket”);
exit(1);
• socket returns an integer(socket descriptor)
• fd < 0} indicates that an error occurred
• Socket descriptor s are similar to file descriptors
• AF_INET: associates a socket with the internet protocol family
• SOCK_STREAM: selects the TCP protocol
SOCK_DGRAM: selects the UDP protocol
Protocols

• A protocol is a set of rules of communication. Protocols are the building blocks of a network architecture.
• Each protocol object has two different interfaces:
 service interface: operations on this protocol
 peer-to-peer interface: messages exchanged with peer
• Term “protocol” is overloaded
 specification of peer-to-peer interface
 module that implements this interface
Client - Server paradigm
• Server waits for client to request a connection.
• Client contacts server to establish a connection.
• Client sends request.
• Server sends reply.
Client and/or server terminate connection
TCP vs. UDP
• Transmission Control Protocol (TCP)
• One - to - one
• Connection - oriented
• Reliable
• In order delivery
• Transmission after connect
• User Datagram Protocol (UDP)
• One to one or many
• Connectionless
• Unreliable
• Unordered delivery
Transmission with destination addres
Final thoughts
• Make sure to #include the header files that defines used functions
• Check man – pages and web – site for additional information
Reply
#4

[attachment=13075]
Socket Programming
Socket Programming Overview
BSD Unix C Socket Programming API
Handle asynchronous input output from multiple socket descriptors
Soothing words
Don’t worry too much about the sense of information overload you may get from this lecture. There is a lot of detail about sockets that you don’t need to remember, because you can look it up. Pay attention to the patterns and outlines of what’s going on, and use reference material for the details as you program.
Refreshing
Host (NIC card) identified by unique IP address
Network application/process identified by port number
Network connection identified by a 5-tuple (src ip, src port, dst ip, dst port, protocol)
Two kinds of Internet transport services provided to applications
Connection-oriented TCP
Connectionless UDP
Huh?
We haven’t yet covered the transport layer in class, and yet you’re being called on to use sockets to access transport services
This is partly a matter of semester mechanics, and partly because everything has to start somewhere
Treat this as your intro to the essentials of transport, with details to follow
Socket Programming API
API: Application Programming Interface
Socket analogous to door
sending process shoves message out door
sending process assumes transport infrastructure on other side of door that brings message to socket at receiving process
connection between sockets set-up/managed by OS
What APIs Needed?
How to create socket (door)
How to establish connection
Client connects to a server
Server accepts client req.
How to send/recv data
How to identify socket
Bind to local address/port
How to close socket (door)
How to create socket
How to send/recv data
How to identify socket
How to close socket
Socket: Conceptual View
Another conceptual view
But why?
Sockets provide a (mostly) uniform API to access many different network services
Services may be implemented in the kernel or in user space
Common API across multiple protocol stacks (UNIX domain, IPv4, IPv6, ISO/OSI, Appletalk, SNA, Bluetooth, etc.)
Common API across multiple layers
Creating a Socket
Format: int socket(family, type, protocol);
domain, service and protocol parameters:
family: PF_INET/AF_INET, PF_UNIX/AF_UNIX
service:
SOCK_DGRAM: datagram service (i.e., UDP)
SOCK_STREAM: byte stream service (i.e.,TCP)
protocol: usually 0 for default type
return a socket descriptor, like a file descriptor in Unix
#include <sys/types.h>
#include <sys/socket.h>
if (sd = socket(AF_INET, SOCK_STREAM, 0) <0 ){
perror (”socket”); /* socket creation error */
}
Binding to a Local Address
Format: int bind(int sockid, struct sockaddr *addr, int addresslen);
Servers need to call it
optional for connection-oriented clients
#include <system/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int sd; struct sockaddr_in myaddr;
if (sd = socket(AF_INET, SOCK_DGRAM,0) )<0 {/*socket error*/};
myaddr.sin_family = AF_INET;
myaddr.sin_port = htons(5100); /* > 5000 */
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
/* INADDR_ANY: allow OS to choose IP address for any interface */
if ( bind(sd, (struct sockaddr *) &myaddr, sizeof(myaddr)) < 0)
{ /* bind error */ }
};
Socket Address Structures
Predefined data structures:
struct sockaddr_in { /* INET socket address info */
short sin_family; /* set me to AF_INET */
u_short sin_port; /* 16 bit num, network byte order*/
struct in_addr sin_addr; /* 32 bit host address */
char sin_zero[8]; /* not used */
};
struct in_addr {
unsigned long s_addr; // load with inet_aton()
};
Socket Address Structures
struct sockaddr_in { /* INET socket address info */
short sin_family; /* set me to AF_INET */
u_short sin_port; /* 16 bit num, network byte order*/
struct in_addr sin_addr; /* 32 bit host address */
char sin_zero[8]; /* not used */
};
struct in_addr {
union {
struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
struct { u_short s_w1,s_w2; } S_un_w;
u_long S_addr;
} S_un;
};
#define s_addr S_un.S_addr
Socket Address Structures
struct sockaddr_in { /* INET socket address info */
short sin_family; /* set me to AF_INET */
u_short sin_port; /* 16 bit num, network byte order*/
struct in_addr sin_addr; /* 32 bit host address */
char sin_zero[8]; /* not used */
};
struct sockaddr {
unsigned short sa_family; // address family, AF_xxx char sa_data[14]; // 14 bytes of protocol address
};
find out own IP address
Find out own host name
#include <unistd.h>
int gethostname(char *name, int namelen);
name : is character array way to store the name Of the machine with null terminated character.
namelen : size of the chracter array

This function puts the name of the host in name . It returns 0 if ok, -1 if error.
find out own IP address (cont)
find out own IP address
#include <netdb.h>
struct hostent *gethostbyname(const char *name);
This returns hostent structure with all necessary information related to host with name .
struct hostent {
char *h_name; /* canonical name of host*/
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
};
#define h_addr h_addr_list[0]
hostent
Address stored in h_addr is in struct in_addr form.
To obtain “.” separated ip address we could use
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
char *inet_ntoa(const struct in_addr in);
The routine inet_ntoa() returns a pointer to a string in the base 256 notation d.d.d.d.
CO Server: listen() and accept()
listen():
int listen (int sd, int backlog);
notify OS/network ready to accept requests
backlog: max. listen queue size while waiting for accept()
does not block/wait for requests
accept():
int accept (int sd, struct sockaddr *fromaddr, int addrlen);
use socket (sd) for accepting incoming connection requests
create new socket (return value) for data exchange w/ client
block until client connects, cannot selectively accept
Connecting to Server: connect()
Format:
int connect (int sd, struct sockaddr *toaddr, int addrlen);
Client issues connect() to
establish remote address, port (connection-oriented, connectionless)
establish connection with server (connection-oriented only)
CO: block until accepted or error
fails: server/host not listening to port, timeout
Sending and Receiving Data
Connection-oriented
send() and recv(); or read() and write()
Format
int send(int sockfd, char *buff, int nbytes, int flags)
int recv(int sockfd, char *buff, int nbytes, int flags)
Connectionless
sendto() and recvfrom()
Format
int sendto(int sockfd, char *buff, int nbytes, int flags,
struct sockaddr *to, int addrlen)
int recvfrom(int sockfd, char *buff, int nbytes, int flags,
struct sockaddr *from, int addrlen)

Identifying socket
Getting own address and port associated to a connected socket :
#include <sys/types.h>
#include <sys/socket.h>
int getsockname(int s, struct sockaddr *name, socklen_t *namelen);
returns the current name for socket s. The namelen parameter should be initialized to indicate the amount of space pointed to by name. On return it contains the actual size in bytes of the name returned.
Identifying socket ( cont)
#include <sys/types.h>
#include <sys/socket.h>
int getpeername(int s, struct sockaddr *name, socklen_t *namelen);
returns the name of the peer connected to socket s.
Closing a Socket
Format – int close(int fd)
Call this function to close a created socket.
System takes care of buffered data.

A summary of BSD Socket
BSD Socket Programming Flows (connection-oriented)
BSD Socket Programming (connectionless)
Data Conversion & Name/Address Translation
Integers:
little endian: least significant byte first (e.g., DEC, Intel)
big endian: most significant byte first (e.g., Sun, HP, SGI)
network byte order: big endian
ntohl(): network-to-host byte order conversion, long(32 bits)
htonl(): host-to-network byte order conversion, long(32 bits)
ntohs(), htons(): for short integer (16 bits)
Host name to IP address (numeric): gethostbyname()
Host IP address to name: gethostbyaddr()
IP address conversion:
from numeric to dotted quad: inet_ntoa()
you may need this for printing the IP address of a host
from dotted quad to numeric: inet_addr()
Example of Stream Server: echo
/* stream server: echo what is received from client */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[])
{
int s, t, sinlen;
struct sockaddr_in sin;
char msg[80];

Example of Stream Server: echo (cont’d)
if (argc < 2) {
printf (”%s port\n”, argv[0] ); /* input error: need port no! */
return -1;
}
if ( (s = socket(AF_INET, SOCK_STREAM, 0 ) ) < 0) { /* create socket*/
perror(”socket”); /* socket error */
return -1;
}
sin.sin_family = AF_INET; /*set protocol family to Internet */
sin.sin_port = htons(atoi(argv[1])); /* set port no. */
sin.sin_addr.s_addr = INADDR_ANY; /* set IP addr to any interface */
if (bind(s, (struct sockaddr *)&sin, sizeof(sin) ) < 0 ){
perror(”bind”); return -1; /* bind error */
}
Example of Stream Server: echo (cont’d)
/* server indicates it’s ready, max. listen queue is 5 */
if (listen(s, 5)) {
printf (”listen”); /* listen error*/
return -1;
}
sinlen = sizeof(sin);
while (1) {
/* accepting new connection request from client,
socket id for the new connection is returned in t */
if ( (t = accept(s, (struct sockaddr *) &sin, &sinlen) ) < 0 ){
perror(”accept ”); /* accpet error */
return -1;
}
Example of Stream Server: echo (cont’d)
printf( ”From %s:%d.\n”,
inet_ntoa(sin.sin_addr), ntohs(sin.sin_port) );
if ( read(t, msg, sizeof(msg) ) <0) { /* read message from client */
perror(”read”); /* read error */
return -1;
}
if ( write(t, msg, strlen(msg) ) < 0 ) { /* echo message back */
perror(”write”); return -1; /* write error */
}
/* close connection, clean up sockets */
if (close(t) < 0) { perror(”close”); return -1;}
} // not reach below
if (close(s) < 0) { perror(”close”); return -1;}
return 0;
}
Example of Stream Client: echo
/* stream client: send a message to server */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#inlcude <stdio.h>
#include <netdb.h>
int main (int argc, char *argv[] )
{
int s, n;
struct sockaddr_in sin; struct hostent *hptr;
char msg[80] = ”Hello World!”;
Example of Stream Client: echo (cont’d)
if ( argc < 3 ) {
printf ( ”%s host port\n”, argv[0] ); /* input error: need host & port */
return -1;
}
if ( (s = socket(AF_INET, SOCK_STREAM, 0 ) ) < 0) { /* create socket*/
perror(”socket”); /* socket error */
return -1;
}
sin.sin_family = AF_INET; /*set protocol family to Internet */
sin.sin_port = htons(atoi(argv[2])); /* set port no. */
if ( (hptr = gethostbyname(argv[1]) ) == NULL){
fprintf(stderr, ”gethostname error: %s”, argv[1]);
return = -1;
}
memcpy( &sin.sin_addr, hptr->h_addr, hptr->h_length);
Example of Stream Client: echo (cont’d)
if (connect (s, (struct sockaddr *)&sin, sizeof(sin) ) < 0 ){
perror(”connect”); return -1; /* connect error */
}
if ( write(s, msg, strlen(msg) +1) < 0 ) { /* send message to server */
perror(”write”); return -1; /* write error */
}
if ( ( n = read(s, msg, sizeof(msg) ) ) <0) { /* read message from server */
perror(”read”); return -1; /* read error */
}
printf (” %d bytes: %s\n”, n, msg); /* print message to screen */
/* close connection, clean up socket */
if (close(s) < 0) {
perror(”close”); /* close error */
return -1;}
return 0;
}
Compiling and Executing
hobbes% g++ -o echo-server echo-server.c -lsocket -lnsl
hobbes% g++ -o echo-client echo-client.c -lsocket -lnsl
hobbes% echo-server 5700 &
hobbes% echo-client kepler 5700
From 128.101.34.75:32938.
12 bytes: Hello World!

A Few Words about Port Numbers
1-255: standard services (21 ftp, 25 SMTP, 80 HTTP)
1-1023: available only to system
1024-4095: usable by system & users
5000 - : usable only by users
What We Have Learned
BSD Unix C Socket Programming API
Socket operations: system calls into OS
What we will learn next
Writing server and client to handle asynchronous input output from multiple socket descriptors
scenario
Think about the case when you write a program
Will take input from the std input and also from other multiple connected peers at the same time.
Input from all of descriptors are asynchronous
One possible solution –
Probing all the descriptors in round robin manner for activity
Problem
Wastage of CPU time
Select()
Select() is a system call that lets you probe the operating system to discern whether or not there is I/O to be done on various file descriptors (monitoring several sockets at the same time).
It is way for program to instruct the kernel to wake up this process whenever there is an event detected in any of the descriptor passed to the function as argument.
Select (cont)
#include <sys/time.h>
#include <sys/types.h>
#include <sys/select.h>
int select(int nfds,
fd_set *readfds,
fd_set *writefds,
fd_set *exceptfds,
struct timeval *timeout);
Select Arguments
The nfds argument specifies the range of file descriptors to be tested. The select() function tests file descriptors in the range of 0 to nfds-1.
If the readfds argument is not NULL, it points to an object of type fd_set that on input specifies the file descriptors to be checked for being ready to read, and on output indicates which file descriptors are ready to read.
Select Arguments (cont)
If the writefds argument is not NULL, it points to an object of type fd_set that on input specifies the file descriptors to be checked for being ready to write, and on output indicates which file descriptors are ready to write.
If the exceptfds argument is not NULL, it points to an object of type fd_set that on input specifies the file descriptors to be checked for error conditions pending, and on output indicates which file descriptors have error conditions pending
Select Arguments (timeout)
the timeout argument is not a NULL pointer, it points to an object of type struct timeval that specifies a maximum interval to wait for the selection to complete.
If the timeout argument points to an object of type struct timeval whose members are 0, select() does not block.
Select Arguments (timeout)
If the timeout argument is a NULL pointer, select() blocks until an event causes one of the masks to be returned with a valid (non-zero) value or until a signal occurs that needs to be delivered.
If the time limit expires before any event occurs that would cause one of the masks to be set to a non-zero value, select() completes successfully and returns 0.
Select Arguments (return value)
If successful, select() returns the number of ready descriptors that are contained in the bit masks. If the time limit expires, select returns zero and sets errno to EINTR. On failure, it returns -1 and sets errno to one of the following values:
EBADF 
EINTR 
EISDIR 
EINVAL 
How to set descriptor values for select() arguments
FD_CLR(fd, &fdset)  
Clears the bit for the file descriptor fd in the file descriptor set fdset.
FD_ISSET(fd, &fdset)  -- check for readiness
Returns a non-zero value if the bit for the file descriptor fd is set in the file descriptor set pointed to by fdset, and 0 otherwise.
How to set descriptor values for select() arguments
FD_SET(fd, &fdset)   -- set in order to be monitored
Sets the bit for the file descriptor fd in the file descriptor set fdset.
FD_ZERO(&fdset)  
Initializes the file descriptor set fdset to have zero bits for all file descriptors.
select() Example
servsock = startserver();
FD_ZERO(&livesdset);
FD_SET( servsock, &livesdset);
livesdmax = servsock+1;
While(1){
FD_ZERO(&readset);
readset = livesdset;
nfound = select( livesdmax, &readset, NULL,NULL, NULL);
if( nfound < 0 ){
if( errno == EINTR ) { /* system interrupt handelling */
continue; }
perror( " Select call problem :");
exit(1);
}
/* look for messages from live clients */ /**/
for (frsock=3; frsock < livesdmax; frsock++) {}
}
Reply

Important Note..!

If you are not satisfied with above reply ,..Please

ASK HERE

So that we will collect data for you and will made reply to the request....OR try below "QUICK REPLY" box to add a reply to this page
Popular Searches: socket programming project ideas, ppt on the socket interface system, programming course newcastle, filenames typically include a, programming a directv remote, secure socket connection, socket communication technical seminar,

[-]
Quick Reply
Message
Type your reply to this message here.

Image Verification
Please enter the text contained within the image into the text box below it. This process is used to prevent automated spam bots.
Image Verification
(case insensitive)

Possibly Related Threads...
Thread Author Replies Views Last Post
  Genetic Programming Seminar Report Information Technology 5 16,186 15-03-2012, 01:16 PM
Last Post: seminar paper
  Extreme Programming (XP) computer science crazy 5 4,885 14-03-2012, 11:57 AM
Last Post: seminar paper
  CONTEXT ORIENTED PROGRAMMING project topics 2 2,060 18-08-2011, 10:04 AM
Last Post: seminar addict
Thumbs Up Linux Shell Programming projectsofme 0 1,869 07-10-2010, 04:58 PM
Last Post: projectsofme

Forum Jump: