Sending data in socket server using C
I am beginner in networking and trying to learn writing simple server. I've tried writing a simple socket server using linux manual commands. I have couple of questions. Is it possible to send data as a client to a server, and then pass the data from server to client again? Also, whenever I run my server, I am getting this weird message not sure why.
Also, what could I improve in my code?
Server:
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char* argv[]) {
int socket_serv;
char response[256] = "Connected to server";
socket_serv = socket(AF_INET, SOCK_STREAM, 0);
if(socket_serv == -1) {
perror("Error connecting to server");
}
struct sockaddr_in socket_addr;
socket_addr.sin_family = AF_INET;
socket_addr.sin_port = htons(8080);
socket_addr.sin_addr.s_addr = INADDR_ANY;
bind(socket_serv, (struct sockaddr*) &socket_addr, sizeof(socket_addr));
listen(socket_serv, 50);
accept(socket_serv, NULL, NULL);
send(socket_serv, response, sizeof(response), 0);
return 0;
}
Client:
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char *argv[]) {
int socket_serv;
socket_serv = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in socket_addr;
socket_addr.sin_family = AF_INET,
socket_addr.sin_port = htons(8080);
socket_addr.sin_addr.s_addr = INADDR_ANY;
int status = connect(socket_serv, (struct sockaddr*) &socket_addr, sizeof(socket_addr));
if(status == -1) {
perror("cant connect");
}
char server_res[256];
recv(socket_serv, &server_res, sizeof(server_res), 0);
printf("Data from server: %s", server_res);
close(socket_serv);
return 0;
}
in the server the accept
function should be in the loop:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char* argv[]) {
int socket_serv;
char response[256] = "HTTP/1.1 200 OK\nContent-Length: 20\n\nConnected to server\n";
socket_serv = socket(AF_INET, SOCK_STREAM, 0);
if(socket_serv == -1) {
perror("Error connecting to server");
}
struct sockaddr_in socket_addr;
socket_addr.sin_family = AF_INET;
socket_addr.sin_port = htons(8080);
socket_addr.sin_addr.s_addr = INADDR_ANY;
bind(socket_serv, (struct sockaddr*) &socket_addr, sizeof(socket_addr));
listen(socket_serv, 50);
for (;;) {
int fd = accept(socket_serv, NULL, NULL);
printf("accepted socket: %d\n", fd);
// read request
char rbuf[512];
read(fd, rbuf, 512);
printf("%s", rbuf);
// send response
send(fd, response, strlen(response), 0);
close(fd);
}
return 0;
}
The loop accepts and processes new connections. Note that send
sends strlen(response) bytes, not all 256 bytes.
I put one single read
here. Ideally read
should be in the loop to read all arrived packets.
Test it with curl -v 127.0.0.1:8080