I'm trying to make a program (client) which kan send a message to a server upon request from user. Stripped down code follows:
Client:
int main(int argc, char **argv) {
struct sockaddr_in servaddr;
int sock = socket(AF_INET, SOCK_STREAM, 0);
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(6789);
servaddr.sin_addr.s_addr = inet_addr(<ip_address_of_server>);
while(1) {
char message[161];
fgets(message, 161, stdin);
/* Replacing '\n' with '\0' */
char *tmp = strchr(message, '\n');
if (tmp) *tmp = '\0';
connect(sock, (struct sockaddr *)&servaddr, sizeof(servaddr));
send(sock, message, strlen(message), 0);
close(sock);
}
}
Server:
int main(int argc, char **argv) {
struct sockaddr_in servaddr;
int sock = socket(AF_INET, SOCK_STREAM, 0);
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(6789);
bind(sock, (struct sockaddr *)&servaddr, sizeof(servaddr));
listen(sock, 5);
while(1) {
int clisock = accept(sock, (struct sockaddr *) NULL, NULL);
if (clisock >= 0) {
int messageLength = 160;
char message[messageLength+1];
int in, index = 0, limit = messageLength;
while ((in = recv(clisock, &message[index], messageLength, 0)) > 0) {
index += in;
limit -= in;
}
printf("%s\n", message);
}
close(clisock);
}
}
Now, this works for the first message I send. But then it is not able to make another connection (I get the error message "Bad file descriptor" when trying to connect in the Client program.) Can anyone see what I have misunderstood? Thank you :)
The sendmmsg() system call is an extension of sendmsg(2) that allows the caller to transmit multiple messages on a socket using a single system call. (This has performance benefits for some applications.) The sockfd argument is the file descriptor of the socket on which data is to be transmitted.
The send() and recv() calls specify: The socket s on which to communicate. The address in storage of the buffer that contains, or will contain, the data (addr_of_data, addr_of_buffer) The size of this buffer (len_of_data, len_of_buffer)
The recv() call applies only to connected sockets. This call returns the length of the incoming message or data.
your client programme also does the same mistake, first time you open the socket but after the first connection is done you close the socket, so the next time in the loop the socket descriptor is not valid, you need to re-open the socket but that's missing, please remove the socket call from top and add the below line in the start of while loop
int sock = socket(AF_INET, SOCK_STREAM, 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With