Visit Our UNIX and Linux User Community


C - HTTP Socket Programming


 
Thread Tools Search this Thread
Top Forums Programming C - HTTP Socket Programming
# 1  
Old 04-07-2009
C - HTTP Socket Programming

Hello everybody,

I learning socket programming in C and was wondering if anybody here could help me out.

I have two .c programs namely server.c and client.c .......

The client sends a message and the server in turn returns the value.

Basically I want to send in a request to a webserver say at port 80 in form of
Quote:
GET \DATA.HTML HTTP/1.1\r\n
and in return get value dumped back.

Here are the codes for Server.c and Client.c

Server.c
Code:
#include <stdio.h>      /* for printf() and fprintf() */ 
#include <sys/socket.h> /* for socket(), bind(), and connect() */ 
#include <arpa/inet.h>  /* for sockaddr_in and inet_ntoa() */ 
#include <stdlib.h>     /* for atoi() and exit() */ 
#include <string.h>     /* for memset() */ 
#include <unistd.h>     /* for close() */ 
 
#define RCVBUFSIZE 64   /* Size of receive buffer */ 
#define MAXPENDING 5    /* Maximum outstanding connection requests */ 
 
void DieWithError(char *errorMessage);  /* Error handling function */ 
void HandleTCPClient(int clntSocket);   /* TCP client handling function */ 
 
int main(int argc, char *argv[]) 
{ 
    int servSock;                    /* Socket descriptor for server */ 
    int clntSock;                    /* Socket descriptor for client */ 
    struct sockaddr_in echoServAddr; /* Local address */ 
    struct sockaddr_in echoClntAddr; /* Client address */ 
    unsigned short echoServPort;     /* Server port */ 
    unsigned int clntLen;            /* Length of client address data structure */ 
 
    if (argc != 2)     /* Test for correct number of arguments */ 
    { 
        fprintf(stderr, "Usage:  %s <Server Port>\n", argv[0]); 
        exit(1); 
    } 
 
    echoServPort = atoi(argv[1]);  /* First arg:  local port */ 
 
    /* Create socket for incoming connections */ 
    if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) 
        DieWithError("socket() failed"); 
       
    /* Construct local address structure */ 
    memset(&echoServAddr, 0, sizeof(echoServAddr));   /* Zero out structure */ 
    echoServAddr.sin_family = AF_INET;                /* Internet address family */ 
    echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ 
    echoServAddr.sin_port = htons(echoServPort);      /* Local port */ 
 
    /* Bind to the local address */ 
    if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) 
        DieWithError("bind() failed"); 
 
    /* Mark the socket so it will listen for incoming connections */ 
    if (listen(servSock, MAXPENDING) < 0) 
        DieWithError("listen() failed"); 
 
    for (;;) /* Run forever */ 
    { 
        /* Set the size of the in-out parameter */ 
        clntLen = sizeof(echoClntAddr); 
 
        /* Wait for a client to connect */ 
        if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr,  
                               &clntLen)) < 0) 
            DieWithError("accept() failed"); 
 
        /* clntSock is connected to a client! */ 
 
        printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr)); 
 
        HandleTCPClient(clntSock); 
    } 
    /* NOT REACHED */ 
}//-- end main --// 
 
 
 
// 
//// 
// 
void DieWithError(char *errorMessage) 
{ 
    perror(errorMessage); 
    exit(1); 
} 
 
 
 
// 
//// 
// 
void HandleTCPClient(int clntSocket) 
{ 
    char echoBuffer[RCVBUFSIZE];        /* Buffer for echo string */ 
    int recvMsgSize;                    /* Size of received message */ 
 
    /* Receive message from client */ 
    if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0) 
        DieWithError("recv() failed"); 
 
    /* got incoming request from client in the echobuffer */ 
    recvMsgSize = sprintf(echoBuffer, 
                          "MOTOR=0,TEMPS are 3A,42,FA,99");//reply!  
 
    /* Send received string and receive again until end of transmission */ 
    while (recvMsgSize > 0)      /* zero indicates end of transmission */ 
    { 
        /* Echo message back to client */ 
        if (send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize) 
            DieWithError("send() failed"); 
 
        /* See if there is more data to receive */ 
        if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0) 
            DieWithError("recv() failed"); 
    } 
 
    close(clntSocket);    /* Close client socket */ 
}

Client.c
Code:
#include <stdio.h>      /* for printf() and fprintf() */ 
#include <sys/socket.h> /* for socket(), connect(), send(), and recv() */ 
#include <arpa/inet.h>  /* for sockaddr_in and inet_addr() */ 
#include <stdlib.h>     /* for atoi() and exit() */ 
#include <string.h>     /* for memset() */ 
#include <unistd.h>     /* for close() */ 
 
#define RCVBUFSIZE 64   /* Size of receive buffer */ 
 
void DieWithError(char *errorMessage);  /* Error handling function */ 
 
int main(int argc, char *argv[]) 
{ 
    int sock;                        /* Socket descriptor */ 
    struct sockaddr_in echoServAddr; /* Echo server address */ 
    unsigned short echoServPort;     /* Echo server port */ 
    char *servIP;                    /* Server IP address (dotted quad) */ 
    char *echoString;                /* String to send to echo server */ 
    char echoBuffer[RCVBUFSIZE];     /* Buffer for echo string */ 
    unsigned int echoStringLen;      /* Length of string to echo */ 
    int bytesRcvd, totalBytesRcvd;   /* Bytes read in single recv()  
                                        and total bytes read */ 
 
    if ((argc < 3) || (argc > 4))    /* Test for correct number of arguments */ 
    { 
       fprintf(stderr, "Usage: %s <Server IP> <Echo Word> [<Echo Port>]\n", 
               argv[0]); 
       exit(1); 
    } 
 
    servIP = argv[1];             /* First arg: server IP address (dotted quad) */ 
    echoString = argv[2];         /* Second arg: string to echo */ 
 
    if (argc == 4) 
        echoServPort = atoi(argv[3]); /* Use given port, if any */ 
    else 
        echoServPort = 7;  /* 7 is the well-known port for the echo service */ 
 
    /* Create a reliable, stream socket using TCP */ 
    if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) 
        DieWithError("socket() failed"); 
 
    /* Construct the server address structure */ 
    memset(&echoServAddr, 0, sizeof(echoServAddr));     /* Zero out structure */ 
    echoServAddr.sin_family      = AF_INET;             /* Internet address family */ 
    echoServAddr.sin_addr.s_addr = inet_addr(servIP);   /* Server IP address */ 
    echoServAddr.sin_port        = htons(echoServPort); /* Server port */ 
 
    /* Establish the connection to the echo server */ 
    if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) 
        DieWithError("connect() failed"); 
 
    echoStringLen = strlen(echoString);          /* Determine input length */ 
 
    /* Send the string to the server */ 
    if (send(sock, echoString, echoStringLen, 0) != echoStringLen) 
        DieWithError("send() sent a different number of bytes than expected"); 
 
    /* Receive the same string back from the server */ 
    totalBytesRcvd = 0; 
    printf("Received: ");                /* Setup to print the echoed string */ 
    while (totalBytesRcvd < echoStringLen) 
    { 
        /* Receive up to the buffer size (minus 1 to leave space for 
           a null terminator) bytes from the sender */ 
        if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0) 
            DieWithError("recv() failed or connection closed prematurely"); 
        totalBytesRcvd += bytesRcvd;   /* Keep tally of total bytes */ 
        echoBuffer[bytesRcvd] = '\0';  /* Terminate the string! */ 
        printf("%s", echoBuffer);      /* Print the echo buffer */ 
    } 
 
    printf("\n");    /* Print a final linefeed */ 
 
    close(sock); 
    exit(0); 
}//-- end main --// 
 
 
 
// 
//// 
// 
void DieWithError(char *errorMessage) 
{ 
    perror(errorMessage); 
    exit(1); 
}

Please advice as how I could achieve this.Smilie
Any sort of example will be great!

Last edited by kev_1234; 04-07-2009 at 10:22 PM..
# 2  
Old 04-08-2009
Thank you for using code tags. Smilie

It means changing the logic on the client code a little. For starters, being able to get things by hostname instead of IP is nice:

Code:
#include <netdb.h>
...
    echoServAddr.sin_family      = AF_INET;             /* Internet address family */
    {
      struct in_addr a;
      struct hostent *h=gethostbyname(servIP);
      if(h == NULL)
        DieWithError("Unknown host");

      memcpy(&a, h->h_addr_list[0], sizeof(a));

      servIP=inet_ntoa(a);
    }
    echoServAddr.sin_addr.s_addr = inet_addr(servIP);   /* Server IP address */
...

After that I can already get limited output from web pages:
Code:
$ ./client mywebsite 'GET /
' 80
Received: 
<!-- Beginning of page_begin() output -->
<html><head>
  <titl
$

Notice the newline at the end of 'GET /', that is necessary.

Then you modify the receiving loop to receive as much data as it can until the loop breaks.

Note that there are a lot of HTTP standards that this does not comply to. for one thing, it doesn't tell the server it which website it wants to connect to, so it could easily be given the wrong page, and for another thing, it won't correctly parse multi-part web pages. Unless you really, absolutely need to make a new tool for this, the wget commandline tool is a full-featured standards-compliant way to automatically retrieve pages from the web.
# 3  
Old 04-08-2009
Thanks 'Corona68' for the helpSmilie
I will tryout your code and get back to you.
# 4  
Old 04-12-2009
Thanks again for your help.....

The example you gave me get the data alright......but how could I modify it further
so that I could put in a request on the client side on certain port
Quote:
"GET /index.shtml HTTP/1.1\r\nHOST: www.cs.iastate.edu\r\n\r\n".
and then on the server side get a message saying
Quote:
received request from XX.XXX.XX.X
Thanks in Advance
# 5  
Old 04-14-2009
There's plenty of examples of printf and argument handling in the code. What precisely is the sticking point?
# 6  
Old 04-14-2009
Quote:
Originally Posted by Corona688
There's plenty of examples of printf and argument handling in the code. What precisely is the sticking point?
Right! Well main thing I want is to GET the 'index.html' of a website at PORT 80 and then have a message up on the server.c saying "handling request"...etc

Thanks
# 7  
Old 04-14-2009
Yes, I understand that's what you want to do, I'm wondering what's the sticking point in doing so. Are you having trouble figuring out where in the program logic these things need to be put? Are you trying to figure out how to accept a parameter on the command line? Are the finer points of printf a problem? Or am I off the mark and you need some other information? As is you're asking me to do everything and the idea is to teach...

Previous Thread | Next Thread
Test Your Knowledge in Computers #234
Difficulty: Easy
The ARPANET was started to create a Command and Control System that would survive a nuclear attack.
True or False?

10 More Discussions You Might Find Interesting

1. Programming

socket programming

how to include socket.h in visual studio 2005.. (2 Replies)
Discussion started by: asd123
2 Replies

2. Shell Programming and Scripting

sending http url through http socket programming..

hi am senthil am developing a software to send and receive SMS using HTTP connection first of all am forming a URL and sending that URL to a remote server using my Client Program i send that url through Socket(using Send() Function) if i send more than one URL one by one using the same... (4 Replies)
Discussion started by: senkerth
4 Replies

3. Programming

sending http url through http socket programming..

hi am senthil am developing a software to send and receive SMS using HTTP connection first of all am forming a URL and sending that URL to a remote server using my Client Program i send that url through Socket(using Send() Function) if i send more than one URL one by one using the same... (0 Replies)
Discussion started by: senkerth
0 Replies

4. Programming

unable to get end of file while reading HTTP data from socket

I am trying to read HTTP data from a socket. However, for the final set of data being read using read(), read blocks and the control doesnt come back for further processing. I tried using select, but it didn't work... Any help would be greatly acknowledged.:) (2 Replies)
Discussion started by: Harish.joshi
2 Replies

5. IP Networking

socket programming

Hello Everyone Iam working on tcp/ip programming.with some time interval server has to send data.client has to close the connection and to open the connection between the time interval.this is the scenario when iam closing the connection in client side the connection terminates.how to... (1 Reply)
Discussion started by: sureshvaikuntam
1 Replies

6. Programming

HTTP Keep-Alive socket problem

Hello everyone, I am a newbie in UNIX/Linux socket programming. This is a class project that I had trouble with. ================================================== I was trying to make “Keep-Alive” HTTP connections to the server in a tiny web crawler project. Here is the problem: when I tried... (0 Replies)
Discussion started by: imdupeng
0 Replies

7. Programming

Socket programming

Hello!:) I'm trying to do some socket programming based on the following situation: I have a directory service named Casino that will hold all the information regarding the gamers that will try to connect to it in order to play a game(for example (Blackjack).Once they make the login they are... (4 Replies)
Discussion started by: maracumbigo
4 Replies

8. IP Networking

socket programming

my system is a stand alone system... i want to try doing socket porgramming..ihave heard that this is usually done during testing... how can i do that....? (6 Replies)
Discussion started by: damn_bkb
6 Replies

9. Programming

Socket Programming socket

Hello, I actually try to make client-server program. I'm using SCO OpenServer Release 5.0.0 and when I try to compile my code (by TELNET) I've got this error : I'm just using this simple code : and I get the same error if I use : If someone can help me, Thanks (2 Replies)
Discussion started by: soshell
2 Replies

10. Programming

Socket Programming

Dear Reader, Is there any way to check up socket status other than 'netstatus ' Thanks in advance, (1 Reply)
Discussion started by: joseph_shibu
1 Replies

Featured Tech Videos