09 March, 2015

Lect-16 (Socket Functions)

Functions Description in TCP and UDP socket programming
Before going to understand the TCP socket programming you must have to understand the working of various system calls and inbuilt functions that are using in programming. Those system calls and functions ar given below.

1.  Socket - creates a socket for network communications.  Returns a file descriptor for the socket.
Syntax:  int fd = Socket (family, type, protocol)
Family- IPv4 or IPv6
Type- TCP or UDP
Protocol: 0 not used for internet socket.

2. Bind - used by server process to associate an end-point address with a socket.  Must include the port and server address with this call.
Syntax: Bind(Fd,addr,addrlen)
Addr: Pointer to a struct sockaddr
Addrlen: Size of the struct in byte

3. Listen - used by server process to indicate that it is ready to receive connections
Syntax: Listen(fd, backlog)
Backlog: Maximum no of connection

4. Connect - called by the client process to establish a connection between it and a server process.  Need the server's address and port number. 
Syntax: Connect(Fd,addr,addrlen)
Addr: Pointer to a struct sockaddr
Addrlen: Size of the struct in byte

5. Accept - called by the server process to accept a connection.   If no client is trying to connect the call will block. 
Syntax: accept(fd, (struct sockaddr*)NULL, NULL);
sockaddr*: An optional pointer to a buffer that receives the address of the connecting entity, as known to the communications layer. The exact format of the addr parameter is determined by the address family that was established when the socket from the sockaddr structure was created.
addrlen : An optional pointer to an integer that contains the length of structure pointed to by the addr parameter.


6. Memset function:
The C library function void *memset(void *str, int c, size_t n) copies the character c (an unsigned char) to the first n characters of the string pointed to by the argument str.
           
void *memset(void *str, int c, size_t n)
Parameters
             ·         str -- This is pointer to the block of memory to fill.
             ·        c -- This is the value to be set. The value is passed as an int, but the function fills the block of               memory using the unsigned char conversion of this value.
             ·         n -- This is the number of bytes to be set to the value.
Return Value
This function returns a pointer to the memory area str.
Example
The following example shows the usage of memset() function.
#include
#include

int main ()
{
   char str[50];

   strcpy(str,"This is string.h library function");
   puts(str);

   memset(str,'$',7);
   puts(str);
  
   return(0);
}
Let us compile and run the above program, this will produce the following result:
This is string.h library function
$$$$$$$ string.h library function

7. Htonal function:
#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
The htonl() function converts the unsigned integer host long from host byte order to network byte order.

8. Htons function:
uint16_t htons(uint16_t hostshort);
The htons() function converts the unsigned short integer host short from host byte order to network byte order.

9. Inet_pton function:
inet_pton - convert IPv4 and IPv6 addresses from text to binary form
#include
int inet_pton(int af, const char *src, void *dst);
 This function converts the character string src into a network  address structure in the af address family, then copies the network  address structure to dst.  The af argument must be either AF_INET or    AF_INET6.

10. Ctime function:
The C library function char *ctime(const time_t *timer) returns a string representing the localtime based on the argument timer.
The returned string has the following format: Www Mmm dd hh:mm:ss yyyy Where Www is the weekday, Mmm the month in letters, dd the day of the month, hh:mm:ss the time, and yyyy the year.

11. Snprintf():
snprintf is essentially a function that redirects the output of printf to a buffer. This is particularly useful for avoiding repetition of a formatted string. You can build a string once and use printf("%s", mystr) instead of print("%d,%s,%f,%d", x,y,z,a) every time, which gets cumbersome with actual variable names.
The function header for snprintf is
int snprintf(char *str, size_t size, const char *format, ...);
*str is the buffer where printf output will be redirected to. size is the maximum number of bytes(characters) that will be written to the buffer, including the terminating null character that snprintf automatically places for you. The format and the optional ... arguments are just the string formats like "%d", myint as seen in printf.

12. Write function:
            int  write(  int  handle,  void  *buffer,  int  nbyte  );
The write() function attempts to write nbytes from buffer to the file associated with handle. On text files, it expands each LF to a CR/LF. The function returns the number of bytes written to the file. A return value of -1 indicates an error, with errno set appropriately.


13. Fputs function:

The C library function int fputs(const char *str, FILE *stream) writes a string to the specified stream up to but not including the null character.
               int fputs(const char *str, FILE *stream)

Parameters

         ·         str -- This is an array containing the null-terminated sequence of characters to be written.
         ·         stream -- This is the pointer to a FILE object that identifies the stream where the string is to                  be written.
This function returns a non-negative value else, on error it returns EOF.
14. Read()
            int  read(  int  handle,  void  *buffer,  int  nbyte );
The read() function attempts to read nbytes from the file associated with handle, and places the characters read into buffer. If the file is opened using O_TEXT, it removes carriage returns and detects the end of the file.
The function returns the number of bytes read. On end-of-file, 0 is returned, on error it returns -1, setting errno to indicate the type of error that occurred.

15. Time_t data type

The time_t datatype is a data type in the ISO C library defined for storing system time values. Such values are returned from the standard time() library function. This type is a typedef defined in the standard header.


16. inet_addr()
This function converts the Internet host address  from IPv4 numbers-and-dots notation into binary data in network byte order. If the input is invalid, INADDR_NONE (usually -1) is returned. Use of this function is problematic because -1 is a valid address (255.255.255.255).

17. sendto():
The sendto() function shall send a message through a connection-mode or connectionless-mode socket. If the socket is connectionless-mode, the message shall be sent to the address specified by dest_addr. If the socket is connection-mode, dest_addr shall be ignored.
Prototype: ssize_t  sendto(int socket, const void *message, size_t length,   int flags, const struct sockaddr *dest_addr, socklen_t dest_len);
The sendto() function takes the following arguments:
Socket:   Specifies the socket file descriptor.
Message: Points to a buffer containing the message to be sent.
Length: Specifies the size of the message in bytes.
Flags: Specifies the type of message transmission.
MSG_EOR
Terminates a record (if supported by the protocol).
MSG_OOB
Sends out-of-band data on sockets that support out-of-band data. The significance and semantics of out-of-band data are protocol-specific.
dest_addr:Points to a sockaddr structure containing the destination address. The length and format of the address depend on the address family of the socket.
dest_len:Specifies the length of the sockaddr structure pointed to by the dest_addr argument.

18. Rcvfrom():
The recvfrom() function shall receive a message from a connection-mode or connectionless-mode socket. It is normally used with connectionless-mode sockets because it permits the application to retrieve the source address of received data.
Prototype: ssize_t recvfrom(int socket, void *restrict buffer, size_t length,  int flags, struct sockaddr *restrict address,  socklen_t *restrict address_len);
The recvfrom() function takes the following arguments:
Socket:   Specifies the socket file descriptor.
Buffer:    Points to the buffer where the message should be stored.
Length:   Specifies the length in bytes of the buffer pointed to by the buffer argument.
Flags:     Specifies the type of message reception. Values of this argument are formed by logically OR'ing zero or more of the following values:
MSG_PEEK, MSG_OOB, MSG_WAITALL
Address: A null pointer, or points to a sockaddr structure in which the sending address is to be stored. The length and format of the address depend on the address family of the socket.
address_len: Specifies the length of the sockaddr structure pointed to by the address argument.
The recvfrom() function shall return the length of the message written to the buffer pointed to by the buffer argument. For message-based sockets.

18. Sockaddr():

The sockaddr_storage structure shall contain at least the following members:
sa_family_t   ss_family
When a sockaddr_storage structure is cast as a sockaddr structure, the ss_family field of the sockaddr_storage structure shall map onto the sa_family field of the sockaddr structure. When a sockaddr_storage structure is cast as a protocol-specific address structure, the ss_family field shall map onto a field of that structure that is of type sa_family_t and that identifies the protocol's address family.

19. Socklen_t:

socklen_t, which is an unsigned opaque integral type of length of at least 32 bits.

Lect-16 (Socket Implementation)

TCP Server Socket
#include “sys/socket.h> “
#include “netinet/in.h”
#include “arpa/inet.h”
#include “stdio.h”
#include “stdlib.h”
#include “unistd.h”
#include “errno.h”
#include “string.h”
#include “sys/types.h”
#include “time.h”
int main(int argc, char *argv[])
{
    int listenfd = 0, connfd = 0;
    struct sockaddr_in serv_addr;
    char sendBuff[1025];
    time_t ticks;
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&serv_addr, '0', sizeof(serv_addr));
    memset(sendBuff, '0', sizeof(sendBuff));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(5000);
    bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
    listen(listenfd, 10);
    while(1)
    {
        connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
        ticks = time(NULL);
        snprintf(sendBuff, sizeof(sendBuff), "%.24s\r\n", ctime(&ticks));
        write(connfd, sendBuff, strlen(sendBuff));
        close(connfd);
        sleep(1);
     }
}




TCP Client Socket
#include “sys/socket.h> “
#include “netinet/in.h”
#include “arpa/inet.h”
#include “stdio.h”
#include “stdlib.h”
#include “unistd.h”
#include “errno.h”
#include “string.h”
#include “sys/types.h”
#include “time.h”
int main(int argc, char *argv[])
{
    int sockfd = 0, n = 0;
    char recvBuff[1024];
    struct sockaddr_in serv_addr;
    if(argc != 2)
    {
        printf("\n Usage: %s \n",argv[0]);
        return 1;
    }
    memset(recvBuff, '0',sizeof(recvBuff));
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("\n Error : Could not create socket \n");
        return 1;
    }
   memset(&serv_addr, '0', sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(5000);
    if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)
    {
        printf("\n inet_pton error occured\n");
        return 1;
    }
    if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
       printf("\n Error : Connect Failed \n");
       return 1;
    }
    while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0)
    {
        recvBuff[n] = 0;
        if(fputs(recvBuff, stdout) == EOF)
        {
            printf("\n Error : Fputs error\n");
        }
    }
    if(n < 0)
    {
       printf("\n Read error \n");
    }
    return 0;
}


Compile and Run
Firstly Compile and Run the server file on Terminal 1.
Now Compile and Run the client file in Terminal 2, with server IP address.
Now Run client on Terminal 2
$ ./a.out 127.0.0.1 (For same M/C)
Output:
Sun Dec  18 22:22:14 2011on the its socket descriptor.