Tutorial Socket
Tutorial Socket
Tutorial Socket
2. Assign transport
endpoint an 3. Determine address
address: bind() of server
CONNECTION-ORIENTED SERVICE
2. Assign transport
2. Assign transport
endpoint an
endpoint an
address (optional):
address: bind( )
bind( )
3. Announce willing
to accept connections: 3. Determine address
listen( ) of server
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
ptrh = gethostbyname(host);
if( ((char *) ptrh) == NULL)
{ fprintf( stderr, "invalid host: %s\n", host);
exit(1);
} Example
Client
memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length);
if ( ((int)(ptrp = getprotobyname("tcp"))) == 0)
{ fprintf( stderr, "cannot map \"tcp\" to protocol number\n");
exit(1);
}
closesocket(sd);
exit(0);
}
Example
Client
/* to compile me on Solaris, type: gcc -o server server.c -lsocket -
lnsl */
/* to compile me in Linux, type: gcc -o server server.c */
#include <stdio.h>
#include <string.h>
Example
int visits = 0; /* counts client connections */
Server
/*----------------------------------------------------------------------------
* Program: server
*
* Purpose: allocate a socket and then repeatedly execute the
folllowing:
* (1) wait for the next connection from a client
* (2) send a short message to the client
* (3) close the connection
* (4) go back to step (1)
*
* Syntax: server [ port ]
*
* port - protocol port number to use
*
* Note: The port argument is optional. If no port is specified,
* the server uses the default given by PROTOPORT.
*
Example
*----------------------------------------------------------------------------*/
Server
main (argc, argv)
int argc;
char *argv[];
{
struct hostent *ptrh; /* pointer to a host table entry */
struct protoent *ptrp; /* pointer to a protocol table entry */
struct sockaddr_in sad; /* structure to hold server's address
*/
struct sockaddr_in cad; /* structure to hold client's address
*/
int sd, sd2; /* socket descriptors */
int port; /* protocol port number */
int alen; /* length of address */
char buf[1000]; /* buffer for string the server sends */
if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) {
fprintf(stderr, "cannot map \"tcp\" to protocol
number");
exit (1);
}
/* Create a socket */
sd = socket (PF_INET, SOCK_STREAM, ptrp->p_proto);
if (sd < 0) {
fprintf(stderr, "socket creation failed\n");
exit(1);
}
Example
Server
/* Bind a local address to the socket */
if (bind(sd, (struct sockaddr *)&sad, sizeof (sad)) < 0)
{
fprintf(stderr,"bind failed\n");
exit(1);
}
/* Specify a size of request queue */
if (listen(sd, QLEN) < 0) {
fprintf(stderr,"listen failed\n");
exit(1);
}
Example
Server
/* Main server loop - accept and handle requests */
printf("Server up and running.\n");
while (1) {
alen = sizeof(cad);
fprintf( stderr, "SERVER: Waiting for contact ...\n");