Help with sockets in C


 
Thread Tools Search this Thread
Top Forums Programming Help with sockets in C
# 15  
Old 04-01-2011
Code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 

#ifndef PORT
#define PORT 30758  
#endif

#define MAXDATASIZE 1000 
#define CONSIGNMENT 8

typedef struct client_list {
    char *client_name;
    int client_socket_fd;
    struct client_list *next;
} client;

typedef struct item_list {
    char *name;
    char *number;
    char *current_price;
    char *minimum_price;
    char *num_of_bids_left;
    char *is_closed;
    struct item_list *next;
} item;

void error(const char *error_message) {
    perror(error_message);
    exit(1);
}

int str_len(char *string) {
    int count = 0;
    while(*(string+count)!= '\n' && *(string+count)!= '\0') count++;
    return count;
}

void send_message(int client_socket_fd, char *message, int length) {
    if (write(client_socket_fd, message, length) < 0) error("ERROR writing to socket");
}

void read_message(int socket_fd, char *buffer, int display) {
    size_t bytes; bzero(buffer,MAXDATASIZE);
    if((bytes = read(socket_fd, buffer, MAXDATASIZE)) < 0) error("ERROR reading from socket");    
    if (display) write(1,buffer,bytes);
}

void send_items(item *item_list, int client_socket_fd) {
    send_message(client_socket_fd, "Items available are:\n", 21);
    while(item_list) {
        send_message(client_socket_fd, item_list->number, str_len(item_list->number));
        send_message(client_socket_fd, ".\nItem Name: ", 13);
        send_message(client_socket_fd, item_list->name, str_len(item_list->name));
        send_message(client_socket_fd, "\nCurrent Price: $", 17);
        send_message(client_socket_fd, item_list->current_price, str_len(item_list->current_price));
        send_message(client_socket_fd, "\nNumber Of Bids Left: ", 22);
        send_message(client_socket_fd, item_list->num_of_bids_left, str_len(item_list->num_of_bids_left));
        send_message(client_socket_fd, "\nIs Closed: ", 12);
        send_message(client_socket_fd, item_list->is_closed, str_len(item_list->is_closed));
        send_message(client_socket_fd, "\n", 1);
        item_list = item_list->next;
    }
}

int already_there(client *current, char *username) {
    while(current) {
        if (strcmp(current->client_name, username)==0) return(1);
        current = current->next;
    }
    return(0);
}

client *add_client(char *username, client *client_list, int client_socket_fd) {
    client *new_client = (client *)malloc(sizeof(client)); 
    new_client->client_name = username;
    new_client->client_socket_fd = client_socket_fd;
    new_client->next = client_list;
    return new_client;
}

item *add_item(char *name, char *number, char *current_price, char *num_of_bids_left, char *is_closed, item *item_list) {
    item *new_item = (item *)malloc(sizeof(item)); 
    new_item->name=name;
    new_item->number=number;
    new_item->current_price=current_price;
    new_item->num_of_bids_left=num_of_bids_left;
    new_item->is_closed=is_closed;
    new_item->next=item_list;
    return new_item;
}

---------- Post updated at 01:29 PM ---------- Previous update was at 01:25 PM ----------

client
Code:
int main(int argc, char *argv[]) {
    int socket_fd;
    struct sockaddr_in server_address;
    struct hostent *server;
    char *username, buffer[MAXDATASIZE];
    if (argc == 3) username = getenv("USER");
    else if (argc == 4) username = argv[3];
    else error("Error, invalid number of arguments, need a hostname, port, and a user name (optional).\n"); 
    bzero(buffer,MAXDATASIZE); 
    socket_fd = socket(AF_INET, SOCK_STREAM, 0); 
    if (socket_fd < 0) error("Error opening socket");
    server = gethostbyname(argv[1]); 
    if (server == NULL) error("Error, no such host\n");
    bzero((char *) &server_address, sizeof(server_address)); 
    server_address.sin_family = AF_INET;
    bcopy((char *)server->h_addr, (char *)&server_address.sin_addr.s_addr, server->h_length); 
    server_address.sin_port = htons(PORT);
    if (connect(socket_fd,(struct sockaddr *) &server_address,sizeof(server_address)) < 0) error("Error connecting"); 
    send_message(socket_fd, username, str_len(username)); 
    read_message(socket_fd, buffer, 0); 
    if (strcmp(buffer, "Enter")==0) {
        write(1,username,str_len(username)); write(1," successfully connected to ",27); 
        write(1,argv[1],str_len(argv[1])); write(1,"!\n",2);
        send_message(socket_fd, "ok", 2); 
        read_message(socket_fd, buffer, 1); 
    }
    else { 
        write(1,"User ",5); write(1,username,str_len(username)); 
        write(1," already connected to ",22); write(1,argv[1],str_len(argv[1])); write(1,"!\n",2);
        send_message(socket_fd, "ok", 2); 
    }
    close(socket_fd); 
    return 0;
}

---------- Post updated at 01:29 PM ---------- Previous update was at 01:29 PM ----------

so far i only added support for one client at a time
# 16  
Old 04-01-2011
Now that I can see your sending and receiving functions I can rule out some problems.

I don't see why the position of that line would change what the client receives. Could it be that the server's actually only receiving a partial response from the client instead -- the client sends it all but the server doesn't get it?

You can't count on getting data in the same chunks someone sent it as. You might have to check if you got a complete line, and if you didn't, read more.
# 17  
Old 04-01-2011
but how?
if you read it waits until more data comes in, so if you put a while loop, it will just go into an infinite loop?
so really if you read once, doesnt it read everything from the socket?, i tried before putting a while loop around it, but then it just froze, since i assume it had already finished reading everything...
# 18  
Old 04-01-2011
Quote:
Originally Posted by omega666
but how?
if you read it waits until more data comes in, so if you put a while loop, it will just go into an infinite loop?
Have the loop break when a line's complete. Read one character at a time. This means send_message will need to write a \n after every message so the receiver can tell where it ends.

Code:
int pos=0;
bzero(buffer,MAXDATASIZE);

// Stop once we have an entire single line
while((buffer[pos] != '\n') && (pos < MAXDATASIZE))
{
        // Put new data 'pos' bytes ahead, so we don't overwrite the old
        ssize_t b=read(socket_fd, buffer+pos, 1); 
        if(b > 0) pos+=b;
        else break; // b<=0 means socket closed or socket error, so give up.
}

Quote:
so really if you read once, doesnt it read everything from the socket?
The receiving end isn't told how much the sending end sent. The socket doesn't necessarily send all the data at once, either. Plus there's travel time too. It's easily possible to read less than the sender wrote.

I see you've posted the client code now, I'll give it a quick look over.

Last edited by Corona688; 04-01-2011 at 02:58 PM..
# 19  
Old 04-01-2011
your code is only reading one line (as in stops at a \n), but my data that's being sent, can include more than 0 \n's, could that be causing the problem?
but then again, sometimes the problem happens...

maybe somewhere (not at the end) in the data i send, there is a \0...?
# 20  
Old 04-01-2011
I don't see anything obviously wrong with the client code except the problems already mentioned.
# 21  
Old 04-01-2011
since my data can have >0 \n should i just change it to

Code:
int pos=0; 
bzero(buffer,MAXDATASIZE);  // Stop once we have an entire single line 
while((buffer[pos] != '\0') && (pos < MAXDATASIZE)) {        
     // Put new data 'pos' bytes ahead, so we don't overwrite the old        
     ssize_t b=read(socket_fd, buffer+pos, 1);         
     if(b > 0) pos+=b;         
     else break; // b<=0 means socket closed or socket error, so give up. 
}

?

actualy it makes sense, everytime the reading is incomplete, it only read uptil the first \n character...
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

Any example about sockets in C++?

Hi, i am student, think learning about c++, someone has a example the how establish a conection with sockets :b::b: (1 Reply)
Discussion started by: mmartinez
1 Replies

2. Red Hat

Sockets

hai guys, I'm doing a project in which one server communicates with several clients. How can i do it when i have different port numbers???:confused: (0 Replies)
Discussion started by: rajeshb6
0 Replies

3. Programming

Sockets

Hi,i now moved into a different section where i need to use sockets. i am completely nill in sockets. can some body please provide me what are the requirements for a socket. to use sockets in c. thanks (1 Reply)
Discussion started by: MrUser
1 Replies

4. Programming

need help with sockets

anyone and teach me how to save standard output to a file in a client/server socket. I know how to read them to the screen but i'm not quite sure how to save them to a file. my read to screen file code: memset(line, 0x0, LINE_ARRAY_SIZE); while (recv(connectSocket, line, MAX_MSG, 0) >... (1 Reply)
Discussion started by: crunchyuser
1 Replies

5. IP Networking

sockets and firewall

Is it possible to trace the packages and the statuses of client's and/or server's sockets by the UNIX network administrative tools? Two applications interact via sockets. There is no problem if they stay in the same network segment. If their hosts connected through the firewall then they aren't... (4 Replies)
Discussion started by: gogogo
4 Replies

6. Solaris

Sockets in use

Is there a way to see what sockets are in use? The developers here are getting some defunct processes and they would like to get a socket list. This is on a Solaris 8 machine. Thanks! (1 Reply)
Discussion started by: kjbaumann
1 Replies

7. UNIX for Dummies Questions & Answers

sockets

how do i mointor how many sockets are opened from a particular foriegn address? (2 Replies)
Discussion started by: kirpond
2 Replies

8. Programming

sockets

Hai, How cani declare socket and collect the data in a string varialbe. Since i am new to this i am asking this. Can we connect multiple port. Thank you. (6 Replies)
Discussion started by: arunkumar_mca
6 Replies

9. Programming

Sockets!?!?!?!?!?!

I am looking for a way to have a program listen on a port (example: 8000) for communication I will be sending via that port to it(Linux Kernel machine). Once it recieves an appropiate command I need it to run a .bat file in linux. I know what I need to do but I am running into a few problems:... (8 Replies)
Discussion started by: bigB8210
8 Replies

10. Programming

sockets...

Hi ! I had a verry simple question to ask... In unix when we create pipes.. the unnamed pipes that is... is there any way to access those pipes outside the code ? Another thing.. do sockets have an entry in the inode table ? TIA, Devyani. (1 Reply)
Discussion started by: devy8
1 Replies
Login or Register to Ask a Question