Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
Socket client server program, client can create a record and Record is a string of fixed length, known to both client and server.
Here are my code server is
C++
 #include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <sys/time.h>

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <errno.h>

#include <unistd.h>

/* BufferLength is 100 bytes */

#define BufferLength 100

/* Server port number */

#define SERVPORT 3111

 
#pragma pack(1)
struct emprec

{

    int empid;

    char *name;

};
#pragma pack(0)

typedef struct emprec emp;
int main()

{

/* Variable and structure definitions. */

int sd, sd2, rc, length = sizeof(int);

int totalcnt = 0, on = 1;

char temp;

char buffer[BufferLength];

struct sockaddr_in serveraddr;

struct sockaddr_in their_addr;

 

fd_set read_fd;

struct timeval timeout;

timeout.tv_sec = 15;

timeout.tv_usec = 0;

 

/* The socket() function returns a socket descriptor */

/* representing an endpoint. The statement also */

/* identifies that the INET (Internet Protocol) */

/* address family with the TCP transport (SOCK_STREAM) */

/* will be used for this socket. */

/************************************************/

/* Get a socket descriptor */

if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)

{

perror("Server-socket() error");

/* Just exit */

exit (-1);

}

else

printf("Server-socket() is OK\n");

 

/* The setsockopt() function is used to allow */

/* the local address to be reused when the server */

/* is restarted before the required wait time */

/* expires. */

/***********************************************/

/* Allow socket descriptor to be reusable */

if((rc = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on))) < 0)

{

perror("Server-setsockopt() error");

close(sd);

exit (-1);

}

else

printf("Server-setsockopt() is OK\n");

 

/* bind to an address */

memset(&serveraddr, 0x00, sizeof(struct sockaddr_in));

serveraddr.sin_family = AF_INET;

serveraddr.sin_port = htons(SERVPORT);

serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);

 

//printf("Using %s, listening at %d\n", inet_ntoa(serveraddr.sin_addr), SERVPORT);

 

/* After the socket descriptor is created, a bind() */

/* function gets a unique name for the socket. */

/* In this example, the user sets the */

/* s_addr to zero, which allows the system to */

/* connect to any client that used port 3005. */

if((rc = bind(sd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))) < 0)

{

perror("Server-bind() error");

/* Close the socket descriptor */

close(sd);

/* and just exit */

exit(-1);

}

else

    printf("Server-bind() is OK\n");

 

/* The listen() function allows the server to accept */

/* incoming client connections. In this example, */

/* the backlog is set to 10. This means that the */

/* system can queue up to 10 connection requests before */

/* the system starts rejecting incoming requests.*/

/*************************************************/

/* Up to 10 clients can be queued */

if((rc = listen(sd, 10)) < 0)

{

    perror("Server-listen() error");

    close(sd);

    exit (-1);

}

else

    printf("Server-Ready for client connection...\n");

 

/* The server will accept a connection request */

/* with this accept() function, provided the */

/* connection request does the following: */

/* - Is part of the same address family */

/* - Uses streams sockets (TCP) */

/* - Attempts to connect to the specified port */

/***********************************************/

/* accept() the incoming connection request. */

int sin_size = sizeof(struct sockaddr_in);

if((sd2 = accept(sd, (struct sockaddr *)&their_addr, &sin_size)) < 0)

{

    perror("Server-accept() error");

    close(sd);

    exit (-1);

}

else

    printf("Server-accept() is OK\n");

 

/*client IP*/

printf("Server-new socket, sd2 is OK...\n");

//printf("Got connection from the f***ing client: %s\n", inet_ntoa(their_addr.sin_addr));

 

/* The select() function allows the process to */

/* wait for an event to occur and to wake up */

/* the process when the event occurs. In this */

/* example, the system notifies the process */

/* only when data is available to read. */

/***********************************************/

/* Wait for up to 15 seconds on */

/* select() for data to be read. */

FD_ZERO(&read_fd);

FD_SET(sd2, &read_fd);

rc = select(sd2+1, &read_fd, NULL, NULL, &timeout);

if((rc == 1) && (FD_ISSET(sd2, &read_fd)))

{

/* Read data from the client. */

totalcnt = 0;

 

while(totalcnt < BufferLength)

{

/* When select() indicates that there is data */

/* available, use the read() function to read */

/* 100 bytes of the string that the */

/* client sent. */

/***********************************************/

/* read() from client */

rc = read(sd2, &buffer[totalcnt], (BufferLength - totalcnt));

if(rc < 0)

{

    perror("Server-read() error");

    close(sd);

    close(sd2);

    exit (-1);

}

else if (rc == 0)

{

    printf("Client program has issued a close()\n");

    close(sd);

    close(sd2);

    exit(-1);

}

else

{

    totalcnt += rc;

    printf("Server-read() is OK\n");

}

 

}

}

else if (rc < 0)

{

    perror("Server-select() error");

    close(sd);

    close(sd2);

    exit(-1);

}

/* rc == 0 */

else

{

    printf("Server-select() timed out.\n");

    close(sd);

    close(sd2);

    exit(-1);

}

 

/* Shows the data */

printf("Received data from the f***ing client: %s\n", buffer);

 

/* Echo some bytes of string, back */

/* to the client by using the write() */

/* function. */

/************************************/

/* write() some bytes of string, */

/* back to the client. */

printf("Server-Echoing back to client...\n");

rc = write(sd2, buffer, totalcnt);

if(rc != totalcnt)

{

perror("Server-write() error");

/* Get the error number. */

rc = getsockopt(sd2, SOL_SOCKET, SO_ERROR, &temp, &length);

if(rc == 0)

{

    /* Print out the asynchronously */

    /* received error. */

    errno = temp;

    perror("SO_ERROR was: ");

}

else

    printf("Server-write() is OK\n");

 

close(sd);

close(sd2);

exit(-1);

}

 

/* When the data has been sent, close() */

/* the socket descriptor that was returned */

/* from the accept() verb and close() the */

/* original socket descriptor. */

/*****************************************/

/* Close the connection to the client and */

/* close the server listening socket. */

/******************************************/

close(sd2);

close(sd);

exit(0);

return 0;

}



and client is
C++
     #include <stdio.h>

    #include <stdlib.h>

    #include <string.h>

    #include <sys/types.h>

    #include <sys/socket.h>

    #include <netinet/in.h>

    #include <arpa/inet.h>

    #include <netdb.h>

    #include <unistd.h>

    #include <errno.h>

    /* BufferLength is 100 bytes */

    #define BufferLength 100

    /* Default host name of server system. Change it to your default */

    /* server hostname or IP.  If the user do not supply the hostname */

    /* as an argument, the_server_name_or_IP will be used as default*/

    #define SERVER "The_server_name_or_IP"

    /* Server's port number */

    #define SERVPORT 3111

     FILE *fd = NULL;

    /* Pass in 1 parameter which is either the */

    /* address or host name of the server, or */

    /* set the server name in the #define SERVER ... */
#pragma pack(1)
struct emprec

{

    int empid;

    char *name;

};
#pragma pack(0)

typedef struct emprec emp;
char data1[100];
    int main(int argc, char *argv[])

    {

    /* Variable and structure definitions. */

    int sd, rc, length = sizeof(int);

    struct sockaddr_in serveraddr;

    char buffer[BufferLength];

    char server[255];

    char temp;

    int totalcnt = 0;

    struct hostent *hostp;

    char data[100] = "This is a test string from client lol!!! ";

     

    /* The socket() function returns a socket */

    /* descriptor representing an endpoint. */

    /* The statement also identifies that the */

    /* INET (Internet Protocol) address family */

    /* with the TCP transport (SOCK_STREAM) */

    /* will be used for this socket. */

    /******************************************/

    /* get a socket descriptor */

    if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)

    {

    perror("Client-socket() error");

    exit(-1);

    }

    else

    printf("Client-socket() OK\n");

    /*If the server hostname is supplied*/

    if(argc > 1)

    {

    /*Use the supplied argument*/

    strcpy(server, argv[1]);

    printf("Connecting to the f***ing %s, port %d ...\n", server, SERVPORT);

    }

    else

    /*Use the default server name or IP*/

    strcpy(server, SERVER);

     

    memset(&serveraddr, 0x00, sizeof(struct sockaddr_in));

    serveraddr.sin_family = AF_INET;

    serveraddr.sin_port = htons(SERVPORT);

     

    if((serveraddr.sin_addr.s_addr = inet_addr(server)) == (unsigned long)INADDR_NONE)

    {

     

    /* When passing the host name of the server as a */

    /* parameter to this program, use the gethostbyname() */

    /* function to retrieve the address of the host server. */

    /***************************************************/

    /* get host address */

    hostp = gethostbyname(server);

    if(hostp == (struct hostent *)NULL)

    {

    printf("HOST NOT FOUND --> ");

    /* h_errno is usually defined */

    /* in netdb.h */

    printf("h_errno = %d\n",h_errno);

    printf("---This is a client program---\n");

    printf("Command usage: %s <server name or IP>\n", argv[0]);

    close(sd);

    exit(-1);

    }

    memcpy(&serveraddr.sin_addr, hostp->h_addr, sizeof(serveraddr.sin_addr));

    }

     

    /* After the socket descriptor is received, the */

    /* connect() function is used to establish a */

    /* connection to the server. */

    /***********************************************/

    /* connect() to server. */

    if((rc = connect(sd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))) < 0)

    {

    perror("Client-connect() error");

    close(sd);

    exit(-1);

    }

    else

    printf("Connection established...\n");

     

    /* Send string to the server using */

    /* the write() function. */

    /*********************************************/

    /* Write() some string to the server. */
/*
while(1)
{
printf("Enter the choice\n");
printf("1-Insert a new record into file\n");
int choice;
scanf("%d",&choice);

switch(choice)
case 1:
insert();
}
void insert()
{

fd = fopen("/home/tarun/Desktop/test.txt","a+");

   // fp1 = fopen(a, "a+");

    if (fd == NULL)

        perror("");

    else

    {

        printf("Enter the record start with id(int)\n");
gets(data1);
int data_len = strlen(data1);
if(data1>100)
{

printf("cannot insert data since length is greater\n";)

}

else 
{
*/
printf("Sending some string to the f***ing %s...\n", server);
emp temp1;
    //emp temp1 = (emp *)malloc(sizeof(emp));

    temp1.name = (char *)malloc(200 * sizeof(char)); //allocating memory
temp1.empid=3;
temp1.name = "tar";
rc =write(sd,&temp1,sizeof(temp1));

    //rc = write(sd, data, sizeof(data));

     

    if(rc < 0)

    {

    perror("Client-write() error");

    rc = getsockopt(sd, SOL_SOCKET, SO_ERROR, &temp, &length);

    if(rc == 0)

    {

    /* Print out the asynchronously received error. */

    errno = temp;

    perror("SO_ERROR was");

    }

    close(sd);

    exit(-1);

    }

    else

    {

    printf("Client-write() is OK\n");

    printf("String successfully sent lol!\n");

    printf("Waiting the %s to echo back...\n", server);

    }

//}
//}


    
     

    totalcnt = 0;

    while(totalcnt < BufferLength)

    {

     

    /* Wait for the server to echo the */

    /* string by using the read() function. */

    /***************************************/

    /* Read data from the server. */

    rc = read(sd, &buffer[totalcnt], BufferLength-totalcnt);

    if(rc < 0)

    {

    perror("Client-read() error");

    close(sd);

    exit(-1);

    }

    else if (rc == 0)

    {

    printf("Server program has issued a close()\n");

    close(sd);

    exit(-1);

    }

    else

    totalcnt += rc;

    }

    printf("Client-read() is OK\n");

    printf("Echoed data from the f***ing server: %s\n", buffer);

     

    /* When the data has been read, close() */

    /* the socket descriptor. */

    /****************************************/

    /* Close socket descriptor from client side. */

    close(sd);

    exit(0);

    return 0;

    }
Posted
Updated 21-Jul-15 9:20am
v2
Comments
PIEBALDconsult 21-Jul-15 14:51pm    
http://www.tenouk.com/cnlinuxsockettutorials.html
http://www.thegeekstuff.com/2011/12/c-socket-programming/
http://www.binarytides.com/socket-programming-c-linux-tutorial/
http://www.codeproject.com/Articles/10649/An-Introduction-to-Socket-Programming-in-NET-using
CPallini 21-Jul-15 14:53pm    
My virtual 5.
Member 11852878 21-Jul-15 15:21pm    
i have added code can you please check why i am not getting data at server end
Yvan Rodrigues 21-Jul-15 16:50pm    
That won't be enough code for anyone to solve your problem. It's just a list of header files. It could be anything from a bad cable to a buffer overrun.
[no name] 21-Jul-15 17:17pm    
Scroll down, there is some code :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900