Network programming problem regarding imap-client. I am using Dovecod localhost for imap. When I use telnet to check the connection it work perfectly but when C use my C-code to check the connection server send me different output.
The C-code only get error for my loopback ip, it works perfectly when I use different ip to execute the programs.
Here is the output difference screenshot
this is the output diffrence while using telnet and c-code
I tried to change the code little bit but the error give same.
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <stdlib.h>
#define PORT_TIME 13
#define PORT_IMAP 143
#define MAXBUF 1024
int main(int argc,char *argv[])
{
int sockfd;
int n;
struct sockaddr_in dest;
char buffer[MAXBUF],p[MAXBUF],q[MAXBUF];
/*---Open socket for streaming---*/
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
{
perror("Socket");
exit(errno);
}
/*---Initialize server address/port struct---*/
bzero(&dest, sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_port = htons(PORT_IMAP);
if ( inet_aton(argv[1], &dest.sin_addr) == 0 )
{
perror(argv[1]);
exit(errno);
}
if ( connect(sockfd, (struct sockaddr*)&dest, sizeof(dest)) != 0 )
{
perror("Connect ");
exit(errno);
}
else
{
printf("Connected to %s\n",argv[1]);
}
bzero(buffer, MAXBUF);
recv(sockfd, buffer, sizeof(buffer), 0);
printf("%s", buffer);
bzero(buffer,MAXBUF);
bzero(p,MAXBUF);
bzero(q,MAXBUF);
printf(" Name: ");
scanf("%[^\n]%*c",q);
printf(" Password: ");
fgets(p,MAXBUF,stdin);
strcat(buffer,"a1 LOGIN ");
strcat(buffer,q);
strcat(buffer," ");
strcat(buffer,p);
printf("%s",buffer);
if(write(sockfd,buffer,sizeof(buffer))<0)
perror("error on writing");
bzero(buffer, MAXBUF);
recv(sockfd, buffer, sizeof(buffer), 0);
printf("%s", buffer);
bzero(buffer,MAXBUF);
strncpy(buffer,"a2 LIST \"\" \"*\"\r\n",16);
printf("%s",buffer);
if(write(sockfd,buffer,16)<0)
perror("error on writing");
bzero(buffer, MAXBUF);
recv(sockfd, buffer, MAXBUF, 0);
printf("%s", buffer);
close(sockfd);
return 0;
}
When i receive from server it should get me "a2 OK" according to my c-code but it get me "* OK"
The IMAP server is required to do some things in response to your commands, but not forbidden from doing other things.
Most importantly, it can react to incoming mail independently of what commands you send, and its output depends both on the commands you send and those other events to which it also reacts.
Some IMAP servers send occasional * OK whatever for no particular reason, just to keep NAT middleboxes from closing the connection. I don't know why your server sent that * OK, but it's permitted. The server has to eventually send a2 OK, but it can send zero, one, two or 500 * OK responses first. (* OK just means "not an error, not related to any command".)
Related
Although it seems to be correctly implemented, it keeps on returning me ERROR when I establish a connection using the loopback address(127.0.0.1).
In addition to a simple TCP Client/Server connection, I have added an additional case:
If the client tries to send data but finds the connection closed, it is closed too. I perform it by checking if received data is equal to 0 (recv).
Given error:
CLIENT:
Welcome to the Client mode
Please, enter the Server's IP Address and Port (eg. 192.128.192.0 1320)
127.0.0.1 2700
Connected to the server. Now you can send messages
Please, enter a message. Enter "FINISH" if you want to finish the connection
ECHO
client: connection closed ->: Success
(1 bytes)Closing the connection
SERVER:
Hello and welcome to the Server mode
Please, enter the Server's Port (eg. 1320)
2700
Server socket successfully configured
Server listening [Clients allowed: 5]
server: accept error: Bad address
Client implementation:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/ip.h>
/**
struct sockaddr{
uint8_t sa_len; // struct length
sa_family_t sa_family; //protocol family: AF_XXX
char sa_data[8]; //socket addr
}
*/
//void notConnected();
int main(){
struct sockaddr_in serv_addr; //port + ip_addr
int my_socket, tcp_port;
char serv_host_addr[30];
char buffer[1024], inbuff[1024];
int io_buffer;
printf("Welcome to the Client mode\n");
//CONFIGURING THE CONNECTION
my_socket = socket(AF_INET, SOCK_STREAM, 0);//(2)
if(my_socket < 0){
perror("client: socket() error ->");
exit(EXIT_FAILURE);
}
bzero(&serv_addr, sizeof(serv_addr));//(4)
printf("Please, enter the Server's IP Address and Port (eg. 192.128.192.0 1320) \n");
scanf("%s %d", serv_host_addr, &tcp_port);//(1)
serv_addr.sin_family = AF_INET ;
serv_addr.sin_port = htons(tcp_port);
if(inet_pton(AF_INET,serv_host_addr,&serv_addr.sin_addr) < 1){
perror("client: inet_pton() error ->");
exit(EXIT_FAILURE);
}
if((connect(my_socket, (struct sockaddr *) &serv_addr, sizeof(serv_addr) )) < 0)//(5)
{
perror("client: connect() error ->");
exit(EXIT_FAILURE);
}
//ONCE CONNECTED, START THE SENDING/RECEIVING
printf("Connected to the server. Now you can send messages\n");
bzero(&buffer, sizeof(buffer));
while(strcmp(buffer, "OK\n") != 0){
printf("Please, enter a message. Enter \"FINISH\" if you want to finish the connection\n");//(3)
bzero(&buffer, sizeof(buffer));
fgets(buffer, sizeof(buffer), stdin);
io_buffer = send(my_socket, buffer, strlen(buffer),0);//(6)
if(io_buffer < 0){
perror("client: send() error ->");
exit(EXIT_FAILURE);
}
printf("ECHO %s (%d bytes)", buffer, io_buffer);
//RECEIVE AND CHECK IF CONNECTION HAS BEEN CLOSED
io_buffer = recv(my_socket, buffer, sizeof(buffer),0);
if(io_buffer < 0){
perror("client: recv() error ->");
exit(EXIT_FAILURE);
}
else if(io_buffer == 0){ //THIS IS SERVER IS CLOSED
perror("client: connection closed ->");
break;
}
printf("ECHO %s (%d bytes)", buffer, io_buffer);
}
printf("Closing the connection \n");
for(int i=0; i < 5; i++){
printf(". ");
usleep(500000);
}
close(my_socket);
}
Server implementation:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define LISTENQ 5
int main()
{
struct sockaddr_in cli_addr, serv_addr;
char buffer[1024];
int serv_socket, cli_socket, clilen, io_buffer;
int tcp_port;
printf("Hello and welcome to the Server mode\n");
// ASKING FOR PORT NUMBER
if((serv_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0){
perror("server: can't open stream socket");
exit(EXIT_FAILURE);
}
printf("Please, enter the Server's Port (eg. 1320) \n");
scanf("%d", &tcp_port);
// CONFIGURING THE CONNECTION
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(tcp_port);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
// ASSIGNING A NAME TO THE SOCKET
if(bind(serv_socket,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0){
perror("server: can't assign a name to the socket");
exit(EXIT_FAILURE);
}
printf("Server socket successfully configured\n");
printf("Server listening [Clients allowed: %d]\n", LISTENQ);
if(listen(serv_socket, LISTENQ) < 0)
{
perror("server: fail to listen network");
exit(EXIT_FAILURE);
}
// READ & WRITE STREAM
while(1){
//returns a file descriptor for the client
cli_socket = accept(serv_socket,(struct sockaddr *) &cli_addr,(socklen_t *) sizeof(cli_addr));
if(cli_socket < 0){
perror("server: accept error");
exit(EXIT_FAILURE);
}
printf("Server successfully connected to Client\n");
while(1)
{
if ((io_buffer=recv(cli_socket,buffer,sizeof(buffer),0))<0){
perror("ERROR: recv");
exit(EXIT_FAILURE);
}
printf("\"%s\" received from client", buffer);
if(strcmp(buffer, "FINISH") == 0)
{
break;
}
if ((io_buffer=send(cli_socket,buffer,strlen(buffer),0))!=strlen(buffer)){
perror("ERROR: send");
exit(EXIT_FAILURE);
}
bzero(buffer, sizeof(buffer));
}
strcpy(buffer, "OK");
if ((io_buffer=send(cli_socket, buffer, strlen(buffer), 0)) != strlen(buffer)){
perror("ERROR: send");
exit(EXIT_FAILURE);
}
printf("\"OK\" message sent to the Client.\n");
printf("Closing the connection \n");
for(int i=0; i < 5; i++)
{
printf(". ");
usleep(500000);
}
close(cli_socket);
}
}
In your original question, your accept call looks like this:
cli_socket = accept(serv_socket,(struct sockaddr *) &cli_addr,
(socklen_t *) sizeof(cli_addr));
This passes "(socklen_t *) sizeof(cli_addr)" as the third parameter to accept. This is expected to be a pointer to the size of the structure. You should be passing in a pointer to a socklen_t containing the size of the structure passed as parameter two. The size you're currently passing in is being interpreted as an address, which is then causing your program to crash when it is referenced. The code should look like this:
socklen_t cli_addr_size = sizeof(cli_addr);
cli_socket = accept(serv_socket,(struct sockaddr *) &cli_addr,
&cli_addr_size);
I got a task to implement a http server in c code.
it should include handling several connections, but for now I just want to make sure it works with just a single connection.
first, here is my code:
#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>
#define BUF_SIZE 1025
int main(int argc, char **argv)
{
uint16_t portNum = 80;
int connfd = 0, listenFd;
struct sockaddr_in serv_addr, peer_addr;
if ((listenFd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("socket syscall failed: %s.\nExiting...\n", strerror(errno));
exit(EXIT_FAILURE);
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(portNum);
if (bind(listenFd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)))
{
printf("bind syscall failed: %s\nExiting...\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (listen(listenFd, 5))
{
printf("listen syscall failed: %s\nExiting...\n", strerror(errno));
exit(EXIT_FAILURE);
}
while (1)
{
/* new connection */
socklen_t addrsize = sizeof(struct sockaddr_in);
connfd = accept(listenFd, (struct sockaddr *) &peer_addr, &addrsize);
if (connfd < 0)
{
printf("\n Error : Accept Failed. %s \n", strerror(errno));
return 1;
}
char httpRequest[BUF_SIZE] = {0};
if ((recv(connfd, httpRequest, BUF_SIZE, 0)) == -1)
{
printf("recv syscall failed: %s\nExiting...\n", strerror(errno));
exit(EXIT_FAILURE);
}
char msg[BUF_SIZE] = {0};
strcpy(msg, "200 OK THIS IS A TEST");
printf("sending message...\n");
int len = strlen(msg);
if (send(connfd, msg, len, 0) < 0)
{
printf("SEND ERROR\n");
exit(EXIT_FAILURE);
}
printf("message sent!\n");
close(connfd);
close(listenFd);
// THIS IS FOR DEBUG - ignore...
return 0;
}
return EXIT_SUCCESS;
}
here's my problem:
to test my code I ran the following command in another linux terminal:
curl -v loaclhost:80/~/ex.txt
(where ex.txt is simply a test file...)
here is the problem:
I see the http request both in the server and in the curl output, but it seems like the "send" command of the server doesn't work - in the curl window beneath the http rquest it says:
* Empty reply from server
* Connection #0 to host localhost left intact
curl: (52) Empty reply from server
any ideas?
Buffer of 1024 is too small for anything serious. For just playing locally it will work OK. If you ever want to do some serious work buffer of 8192 bytes works fine even for heavy loads.
recv() is in most implementations blocking function, which means that it will block until it receives the entered number of bytes or a client closes the connection after sending data. I didn't see your socket being defined and treated as non-blocking. So that part is up to curl to overcome.
Your HTTP response is wrong.
The header should look like:
"HTTP/1.1 200 OK\r\nStatus: 200 OK\r\nContent-Type: text/plain\r\n\r\n"
You may also add a header:
"Content-Length: 0"
as you aren't sending any data back except the header.
Also, if you continue using HTTP/0.9 or switch to HtTP/1.0, you should close the connection with a client after sending the data to him.
HTTP/1.1 supports opened connection, but it is usually controlled via Keep-Alive and Connection headers.
ok, -1 for me, it didn't work due to the missing '\n' character in strcpy..
First off, this is homework, so please no outright answers. I am writing a back and forth chat program in C. I'm extremely new to C (just started learning for this class). Currently I have three files:
server.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include "chat.h"
#define SERVER_PORT 1725
#define MAX_PENDING 5
#define MAX_LINE 256
int main()
{
struct sockaddr_in sin;
char buf[MAX_LINE];
int len;
int s, new_s;
struct chat_packet packet;
/* build address data structure */
bzero((char *)&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(SERVER_PORT);
/* setup passive open */
if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("simplex-talk: socket");
exit(1);
}
if ((bind(s, (struct sockaddr *)&sin, sizeof(sin))) < 0)
{
perror("simplex-talk: bind");
exit(1);
}
listen(s, MAX_PENDING);
/* wait for connection, then receive and print text */
while(1)
{
if ((new_s = accept(s, (struct sockaddr *)&sin, &len)) < 0)
{
perror("simplex-talk: accept");
exit(1);
}
/* Stay in the following loop until CTRL+C */
while (len = recv(new_s, &packet, sizeof(packet), 0))
{
fputs(packet.sender_name, stdout);
fputs(": ", stdout);
fputs(packet.data, stdout);
fputs("\nYou: ", stdout);
while (fgets(buf, sizeof(buf), stdin))
{
if(strlen(buf) > 144)
{
printf("Your message is too long. Please enter a new message.\n");
continue;
}
else
{
buf[MAX_LINE-1] = '\0';
strncpy(packet.data,buf,144);
char sender[8] = "Mason"; /*should be argv[index of name]*/
strncpy(packet.sender_name, sender, 8);
send(new_s, &packet, sizeof(packet),0);
}
}
}
close(new_s);
}
}
client.c
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include "chat.h"
#define SERVER_PORT 1725
#define MAX_LINE 256
int main(int argc, char * argv[])
{
FILE *fp;
struct hostent *hp;
struct sockaddr_in sin;
char *host;
char buf[MAX_LINE];
int s;
int len;
struct chat_packet packet;
if (argc==2)
{
host = argv[1];
}
else
{
fprintf(stderr, "usage: simplex-talk host\n");
exit(1);
}
/* translate host name into peer's IP address */
hp = gethostbyname(host);
if (!hp) {
fprintf(stderr, "simplex-talk: unknown host: %s\n", host);
exit(1);
}
/* build address data structure */
bzero((char *)&sin, sizeof(sin));
sin.sin_family = AF_INET;
bcopy(hp->h_addr, (char *)&sin.sin_addr, hp->h_length);
sin.sin_port = htons(SERVER_PORT);
/* active open */
if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("simplex-talk: socket");
exit(1);
}
if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
{
perror("simplex-talk: connect");
close(s);
exit(1);
}
/* main loop: get and send lines of text */
while (fgets(buf, sizeof(buf), stdin))
{
if(strlen(buf) > 144)
{
printf("Your message is too long. Please enter a new message.\n");
continue; /*This allows the user to re-enter a message post-error*/
}
else
{
buf[MAX_LINE-1] = '\0';
strncpy(packet.data, buf, 144);
char sender[8] = "Abby"; /*should be argv[index of name]*/
strncpy(packet.sender_name, sender, 8);
send(s, &packet, sizeof(packet), 0);
recv(s, &packet, sizeof(packet),0);
fputs(packet.sender_name, stdout);
fputs(": ", stdout);
fputs(packet.data, stdout);
fputs("\nYou: ", stdout);
}
}
}
chat.h
#include <stdint.h> /* Needed for unsigned types */
#define MAX_DATA_LEN 144 /* So we are on 16-bit boundary */
#define USER_NAME_LEN 8
/* You must send this packet across the socket. Notice there are
* no pointers inside this packet. Why?*/
struct chat_packet {
u_short version; /* 16 bits -- Set to version 2 in code */
char sender_name[8]; /* 64 bits */
char data[MAX_DATA_LEN]; /* Message goes in here */
};
Everything except what is in the client and server while loops were given to me by my instructor. The base part of the assignment is getting back-and-forth chat functionality. I'm running everything in PuTTY using the command line. I duplicate the session and run client in one and server in the other. To run:
./client serverName
./server
I am able to go back and forth one time, and then nothing else sends or receives. I am still able to type, but the two sessions cannot see each other's messages past the first back and forth. I am not sure where my code is wrong. Any advice would be appreciated, as I'm very new to the language. Thanks in advance!
Okay, here's my hint: Think about what happens when you recv() zero characters. Also, check what happens when the server calls accept() vs. when the client calls connect().
You might also want to check the return values of your recv() calls more judiciously. (and send(), for that matter; if a call can fail, check its return value!) Here's a hint from the man recv page:
RETURN VALUES
These calls return the number of bytes received, or -1 if an error occurred.
Also, if you aren't familiar with a debugger (such as gdb), I would recommend learning it. In a pinch, you might consider adding printf() statements to your code, to figure out what is happening.
Also, think about where your "blocking calls" are. If you're not familiar with what it means to be a "blocking call", we call it "blocking" when you call a function, and that function doesn't return ("blocks") until some specified thing happens. For example, your accept() will block until a connection is accepted. Your fgets() will block until a line of text is received. send() would block if you've already sent too much data, and the buffer is full. recv() would block until you've received the specified number of bytes. recv() also has a behavior you might not expect, that you may need to account for:
If no messages are available at the socket, the receive call waits for a
message to arrive, unless the socket is nonblocking (see fcntl(2)) in
which case the value -1 is returned and the external variable errno set
to EAGAIN. The receive calls normally return any data available, up to
the requested amount, rather than waiting for receipt of the full amount
requested; this behavior is affected by the socket-level options
SO_RCVLOWAT and SO_RCVTIMEO described in getsockopt(2).
In your case, your packets might be small enough that you won't run into cases where you have to reassemble them yourself. But it couldn't hurt to check.
I think that gives you some avenues to explore...
i am just starting to learn how to code socket but having problem i can't solve.
so i was trying to create a telnet client and i have succeeded to receive the first message from the server but after this receive line, my program kind of stuck and won't do anything else. not even a simple printf line.
thanks in advance,
Ricky
here's the code:
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
void error_msg(char msg[256]){
printf("error at %s\n", msg);
}
void main(){
struct sockaddr_in serv_addr;
char buffer[2048], server_reply[2048];
printf("trying to connect to []...\n");
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd<0) error_msg("socket");
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr("192.168.0.1");
serv_addr.sin_port = htons(23);
int conn = connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr));
if(conn<0) error_msg("connect");
printf("connected to server\n");
bzero(server_reply, 2048);
bzero(buffer, 2048);
while(1){
int n_recv = recv(sockfd , server_reply , sizeof(server_reply) , 0);
if(n_recv > 0){
printf("%s", server_reply);
sleep(1);
scanf("%s" , buffer);
int n_send = send(sockfd , buffer , sizeof(buffer), 0);
if(n_send < 0) printf("send error, server is not responding...\n");
}
if(n_recv < 0) printf("recv error, server is not responding...\n");
}
close(sockfd);
}
Without knowing exactly what the return value is, it seems likely the remote side has closed the connection:
http://linux.die.net/man/2/recv
The return value will be 0 when the peer has performed an orderly shutdown.
Look at my comment on your question and post that data and I should be able to help more.
The main issue I am having doesn't seem to be in the code itself, however, I posted the code just in case. First, when I run the server and use "telnet localhost 46745" in a separate terminal I get a successful connection to localhost. Then I type "GET /hello.html HTTP/1.1". The hello.html file is located in the directory where the server is being ran from. Anyway, the GET method returns both lines of code in the hello.html file. Okay, that seems to work. The issue lies when I go to firefox, and in the browser type "http://localhost:46745/hello.html", and I don't get any error messages, but the browser just spins and says "Waiting for localhost...". What are some possible issues (code or in browser) that could be causing this issue. I have googled for hours to no avail and, yes, this is a homework assignment. Thanks.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h> /* Internet domain header */
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <signal.h>
#define SA struct sockaddr
#define SERVER_PORT 46745
#define MAX_LINE 256
#define BUFFER_SIZE 10000
#define MAX_PENDING 5
int soc ; /* socket for server */
void signal_catcher( int the_sig ) {
printf("terminating the server socket number %d\n",soc) ;
close( soc ) ;
exit(0) ;
}
int main() {
struct sockaddr_in serv_addr, clnt_addr;
char buf[BUFFER_SIZE];
int len, new_s, bytes_read;
char response[MAX_LINE];
char fileExt[MAX_LINE];
char* token;
/* remove socket for server when terminating */
if( signal(SIGINT, signal_catcher ) == SIG_ERR ){
perror("SIGINT") ;
exit(13) ;
}
if( signal(SIGQUIT, signal_catcher ) == SIG_ERR ){
perror("SIGQUIT") ;
exit(14) ;
}
/* set up listening socket soc, passive open */
if ( (soc = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
perror("server: socket");
exit(1);
}
/* build address data structure */
serv_addr.sin_family = AF_INET ;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY) ;
serv_addr.sin_port = htons(SERVER_PORT) ;
if (bind(soc, (SA *) &serv_addr, sizeof(serv_addr)) < 0) {
perror("server: bind");
close(soc);
exit(1);
}
if(listen(soc, MAX_PENDING) < 0) {
perror("server: listen");
close(soc);
exit(1);
}
printf("Socket number for server = %d\n",soc);
/* accept connection, then receive and print text */
while ( 1 ) {
len = sizeof(clnt_addr) ;
if ( (new_s = accept(soc, (SA *) &clnt_addr , &len) ) < 0 ) {
perror("server: accept");
close(soc);
exit(1);
}
printf("\nConnect from host %s, port %hd\n",inet_ntoa(clnt_addr.sin_addr), ntohs(clnt_addr.sin_port) );
memset(buf,0x0,BUFFER_SIZE); // init line
while( len = recv( new_s, buf, sizeof( buf ), 0 ) ) {
if (strstr(buf,"GET")) {
token=strtok(buf," ");
token=strtok(NULL," ");
sprintf(fileExt,".%s",token);
FILE *fp;
fp=fopen(fileExt, "r");
if (fp!=NULL) {
send(new_s, "HTTP/1.1 200 OK\r\n\r\n", 23, 0);
while(bytes_read=fread(response, 1, sizeof(response), fp)) {
int length = strlen(response)-1;
if(response[length] == '\n') {
response[length] = 0;
}
send(new_s, response, bytes_read, 0 );
fclose(fp);
}
} else {
send(new_s, "HTTP/1.1 404 Not Found\r\n\r\n", 30, 0);
}
}// end if strstr
else {
send(new_s, "HTTP/1.1 400 Invalid Request\r\n\r\n", 36, 0);
}
}// end while from recv
}// end while(1)
close ( new_s );
return(0);
}
There's a few small things wrong in your response to the client. First, you're outputting \n\n before the HTTP/1.1 XXX Some Status line. HTTP/1.1 should be first. There is no \n\n before it. Secondly, you're outputting \ns after it. The HTTP specification specifies that you should use \r\n, not \n (although Firefox should be able to handle this). Finally, for your 400 and 404 status codes, you're not returning any content. You probably should, even if it's empty.
The line terminator is technically CRLF ("\r\n"), not LF ("\n").
This may not be your problem, but it is certainly a problem.
You don't say whether your server is outputting its messages like:
Connect from host ...
so that's one thing to look for. It's possible the messages are never reaching your server.
But, regardless of that, you should get yourself a copy of WireShark (free) or another network sniffer program so you can see exactly what's going on under the covers.
This will greatly assist in debugging these types of issues.