Send a string with sendto() function in C - c

I have to get the numbers in a buffer with recvfrom() function and compute the sum. Then I have to use sprintf() function to get the result as a string and then I have to send this string with sendto() function. Everything is fine is my code except the result that I send with sendto(). Could you help me please ?
int recv_and_handle_message(const struct sockaddr *src_addr, socklen_t addrlen) {
// TODO: Create a IPv6 socket supporting datagrams
// TODO: Bind it to the source
// TODO: Receive a message through the socket
// TODO: Perform the computation
// TODO: Send back the result
int result = 0;
int sock = socket(AF_INET6, SOCK_DGRAM, 0);
if(sock == -1) return sock;
int err = bind(sock,src_addr,addrlen);
if (err == - 1) return err;
struct sockaddr_storage recever;
socklen_t len = sizeof(recever);
char buffer[1024];
int rec = recvfrom(sock, buffer, sizeof(char)*1024, 0, (struct sockaddr*)&recever, &len);
if(rec == -1) return rec;
int*current = (int*)&buffer;
for (int i = 0; i < rec/4; ++i){
result += current[i];
}
char res[1000];
int b = sprintf(res, "%d", result);
if(b == -1){
return -1;
}
char rese[b];
memcpy(rese, res, b);
//for (int i = 0; i < b; ++i){
// rese[i] = res[i];
//}
int r = sendto(sock, &rese, 1, 0, (struct sockaddr *)&recever, len);
if(r == -1){
return -1;
}
return 0;
}

Related

read() not reading the remaining bytes on a socket buffer

I have created two programs, a client and a server. They communicate via sockets sending char arrays of a fixed size of 115 bytes.
The data I want to transfer is stored in the following struct:
typedef struct {
char origin[14];
char type;
char data[100];
} socket_data;
But in order to send the data serialized, I want to send that information in a single string concatenating al the fields in the struct so I send a 115 bytes string. If any of those fields does not reach it's max size, I will manually fill the extra array positions with \0.
I have created two functions implemented in both client and server that send data through the socket or receive data from the socket.
The two functions are the following:
void socket_send(int socket, char *origin, char type, char *data) {
char info[115]; //data to be sent
socket_data aux;
strcpy(aux.origin, origin);
aux.type = type;
strcpy(aux.data, data);
//Filling up the remaining positions of origin and data variables
for (int i = (int) strlen(aux.origin); i<14; i++) aux.origin[i] = '\0';
for (int i = (int) strlen(aux.data); i<100; i++) aux.data[i] = '\0';
//Building up the 115 byte string I want to send via socket
for (int i=0; i<14; i++) info[i] = aux.origin[i];
info[14] = type;
for (int i=0; i<100; i++) info[i+15] = aux.data[i];
ssize_t total_bytes = 115;
ssize_t bytes_written = 0;
//Here I send all the bytes through the socket
do {
bytes_written = write(socket, info + (115 - total_bytes), total_bytes);
total_bytes -= bytes_written;
} while (total_bytes > 0);
}
socket_data socket_rcv(int socket) {
socket_data info;
char sequence[115];
ssize_t total_bytes = 115;
ssize_t bytes_read = 0;
//Here I receive all the bytes from the socket (till I fill up the 115 byte string called sequence)
do {
bytes_read = read(socket, sequence + (115 - total_bytes), total_bytes);
total_bytes -= bytes_read;
} while (total_bytes > 0);
//Then I return a stuct
for (int i=0; i<14; i++) info.origin[i] = sequence[i];
info.type = sequence[14];
for (int i=0; i<100; i++) info.data[i] = sequence[i+15];
return info;
}
As you can see, I loop both read() and write() to make sure all bytes are sent as I'm aware sometimes those functions read or write less bytes than demanded.
The issue is that, testing the functionality of the program, I have seen that in the case that less bytes are read (it loops), the program blocks (maybe waiting for another write() from the server side) instead of reading the remaining bytes in the socket buffer (because all 115 bytes where sent and only 111 received, so there should be still 4 bytes in the socket buffer). Sometimes also, instead of blocking waiting for a possible write(), the program terminates when it shouldn't...
I can't find the issue here and I'd appreciate some help
EDIT
I created this functions to set up the sockets...
Server:
int socketConfig (connection_info cinfo) {
int socketfd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socketfd < 0) {
write(1, "Socket error\n", strlen("Socket error\n"));
return -1;
}
struct sockaddr_in s_addr;
memset (&s_addr, 0, sizeof (s_addr));
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(cinfo.port);
s_addr.sin_addr.s_addr = INADDR_ANY;
if (bind (socketfd, (void *) &s_addr, sizeof (s_addr)) < 0) {
write(1, "Bind error\n", strlen("Bind error\n"));
return -1;
}
listen(socketfd, 3);
return socketfd;
}
int receiveClient(int serverfd) {
struct sockaddr_in client;
socklen_t len = sizeof(client);
return accept(serverfd, (void *) &client, &len);
}
Client:
int connect_to_server(Config config) {
struct sockaddr_in client;
int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
write(1, "Connecting Jack...\n", strlen("Connecting Jack...\n"));
if (sockfd < 0) {
write(1, "Error creating the socket\n", strlen("Error creating the socket\n"));
return -1;
}
memset(&client, 0, sizeof(client));
client.sin_family = AF_INET;
client.sin_port = htons(config.port_jack);
if (inet_aton(config.ip_jack, &client.sin_addr) == 0) {
write(1, "Invalid IP address\n", strlen("Invalid IP address\n"));
return -1;
}
if (connect(sockfd, (void *) &client, sizeof(client)) < 0) {
write(1, "Error connecting to Jack\n", strlen("Error connecting to Jack\n"));
return -1;
}
return sockfd;
}
I can guarantee the connection works
You are not checking the return values of write() and read() for failures.
Try something more like this:
int socket_send_all(int socket, const void *data, size_t size) {
const char *pdata = (const char*) data;
ssize_t bytes_written;
while (size > 0) {
bytes_written = write(socket, pdata, size);
if (bytes_written < 0) return bytes_written;
pdata += bytes_written;
size -= bytes_written;
}
return 0;
}
int socket_rcv_all(int socket, void *data, size_t size) {
char *pdata = (char*) data;
ssize_t bytes_read;
while (size > 0) {
bytes_read = read(socket, pdata, size);
if (bytes_read <= 0) return bytes_read;
pdata += bytes_read;
size -= bytes_read;
}
return 1;
}
int socket_send2(int socket, const socket_data *sd) {
char bytes[115];
memcpy(bytes, sd->origin, 14);
bytes[14] = sd->type;
memcpy(bytes+15, sd->data, 100);
return socket_send_all(socket, bytes, 115);
/* alternatively:
int ret = socket_send_all(socket, sd->origin, 14);
if (ret == 0) ret = socket_send_all(socket, &(sd->type), 1);
if (ret == 0) ret = socket_send_all(socket, sd->data, 100);
return ret;
*/
}
int socket_send(int socket, char *origin, char type, char *data) {
socket_data aux;
strncpy(aux.origin, origin, 14);
aux.type = type;
strncpy(aux.data, data, 100);
return socket_send2(socket, &aux);
}
int socket_rcv2(int socket, socket_data *sd) {
char bytes[115];
int ret = socket_rcv_all(socket, bytes, 115);
if (ret > 0) {
memcpy(sd->origin, bytes, 14);
sd->type = bytes[14];
memcpy(sd->data, bytes+15, 100);
}
return ret;
/* alternatively:
int ret = socket_rcv_all(socket, sd->origin, 14);
if (ret > 0) ret = socket_rcv_all(socket, &(sd->type), 1);
if (ret > 0) ret = socket_rcv_all(socket, sd->data, 100);
return ret;
*/
}
socket_data socket_rcv(int socket) {
socket_data aux;
int ret = socket_rcv2(socket, &aux);
if (ret <= 0) {
// error handling ...
}
return aux;
}
read() returns as many bytes as it wants. Perchance the sent output went out in two packets. Perhaps something else (memory alignment comes to mind). Always handle short reads by trying to read more or have a headache. In addition, write() only writes as many byte as it wants. A short write is usually a full buffer or split by a signal, but stranger things have been observed.
You need to check for errors every time around the loop. Your program as written will trash memory otherwise.

How to use select and accept to communicate with clients properly?

I have read some example and manual about select and accept but I still can't figure out where I did wrong.
I tried to let server communicate with multiple clients. But when I execute server first, then execute client, server will immediately cause segmentation fault( when i == sockfd in server.c). And I tried to print some strings to check which statement cause wrong, it even no print anything after if (i == sockfd). So I really have no idea how to move on, are there any suggestion?
Server.c
char inputBuffer[140] = {};
char message[] = {"Hi,this is server.\n"};
int sockfd = 0,forClientSockfd = 0;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
printf("Fail to create a socket.");
}
//socket creation
struct sockaddr_in serverInfo,clientInfo;
socklen_t addrlen = sizeof(clientInfo);
serverInfo.sin_family = PF_INET;
serverInfo.sin_addr.s_addr = INADDR_ANY;
serverInfo.sin_port = htons(PORT);
bind(sockfd,(struct sockaddr *)&serverInfo,sizeof(serverInfo));
listen(sockfd,5);
fd_set active_fd_set, read_fd_set;
int i;
struct sockaddr_in clientname;
size_t size;
/* Initialize the set of active sockets. */
FD_ZERO (&active_fd_set);
FD_SET (sockfd, &active_fd_set);
int fd_max = sockfd;
while (1)
{
/* Block until input arrives on one or more active sockets. */
//FD_ZERO (&active_fd_set);
//FD_SET (sockfd, &active_fd_set);
read_fd_set = active_fd_set;
if (select (fd_max+1, &read_fd_set, NULL, NULL, NULL) < 0)
{
printf("select fail\n");
}
/* Service all the sockets with input pending. */
for (i = 0; i <= fd_max; ++i)
{
//printf("%d\n",i);
if (FD_ISSET (i, &read_fd_set))
{
//printf("inner :%d %d\n",i,sockfd);
if (i == sockfd)
{
/* Connection request on original socket. */
//printf("A");
int new;
size = sizeof (clientname);
new = accept (sockfd,(struct sockaddr *) &clientname,&size);
if (new < 0)
{
printf("accept fail\n");
}
else
{
printf (
"Server: connect from host %s, port %hd.\n",
inet_ntoa (clientname.sin_addr),
ntohs (clientname.sin_port));
FD_SET (new, &active_fd_set);
if(new > fd_max)
{
fd_max = new;
}
}
}
else
{
/* Data arriving on an already-connected socket. */
if (read_from_client (i) < 0)
{
close (i);
FD_CLR (i, &active_fd_set);
}
}
}
}
}
return 0;
}
int read_from_client (int filedes)
{
char buffer[140];
int nbytes;
nbytes = recv (filedes, buffer, sizeof(buffer),0);
if (nbytes < 0)
{
/* Read error. */
perror ("read");
exit (EXIT_FAILURE);
}
else if (nbytes == 0)
/* End-of-file. */
return -1;
else
{
/* Data read. */
printf ("Server: got message: `%s'\n", buffer);
return 0;
}
}
client.c
int sockfd = 0;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
printf("Fail to create a socket.");
}
//socket connnection
struct sockaddr_in info;
bzero(&info,sizeof(info));
info.sin_family = PF_INET;
//localhost test
info.sin_addr.s_addr = inet_addr(LOCALHOST);
info.sin_port = htons(PORT);
int err;
char *p;
//Send a message to server
err = connect(sockfd,(struct sockaddr *)&info,sizeof(info));
if(err==-1)
printf("Connection error");
while(1)
{
char message[140];
char receiveMessage[140] = {};
fgets(message,140,stdin);
//scanf("%*[^\n]",message);
//printf("%s",message);
/*if(p=strchr(message,'\n')){
*p = 0;
}else{
scanf("%*[^\n]");
scanf("%c");
}
fgets(message,140,stdin);*/
//scanf("%s",message);
send(sockfd,message,sizeof(message),0);
//printf("RCV");
//recv(sockfd,receiveMessage,sizeof(receiveMessage),0);
//printf("%s\n",receiveMessage);
}
thanks !!

C, TCP, recvAll block is not receing anything

I am new to both C and socket programming, so please bear with me. The following code is mostly from Beej networking guide, with some changes. I have the receiver code attached (which is TCP server in this case), that listens to multiple TCP connections. I have a transmitter (client) who is constantly sending fixed chunks of data to this receiver. This code (which I cleaned and removed some function definitions unrelated to my issue) works if instead of calling recv_all function, I only call recv(). But the problem with that I need to do processing on each chunk of received data, so I need the whole chunk. So I thought I should use the recv_all().
Now the problem is it gets stuck in an infinite loop in the while in recv_all(), because n is always 0. I truly appreciate your help.
#define PORT "3490" // the port users will be connecting to
#define BACKLOG 20 // how many pending connections queue will hold
#define MAXDATASIZE 801 // max number of bytes we can get at once
int recv_all(int socket, char *buffer, int *length)
{
int total = 0; // how many bytes we've sent
int bytesleft = *length; // how many we have left to send
int n;
while(total < *length) {
n = recv(socket, buffer+total, bytesleft, 0);
if (n == -1) { break; }
total += n;
bytesleft -= n;
}
*length = total; // return number actually received here
return n==-1?-1:0; // return -1 on failure, 0 on success
}
int main(void)
{
int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
struct sigaction sa;
int yes=1;
char s[INET6_ADDRSTRLEN];
int rv;
double buf[MAXDATASIZE];
int lenRecv;
struct sockaddr_in local_addr; // For the new addition to bind it to an interface
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("server: socket");
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("server: bind");
continue;
}
break;
}
freeaddrinfo(servinfo); // all done with this structure
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
printf("server: waiting for connections...\n");
while(1) { // main accept() loop
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s);
printf("server: got connection from %s\n", s);
if (!fork()) { // this is the child process
close(sockfd); // child doesn't need the listener
for (int i=0; i<1000000; i++) {
int rowInfoSize;
//if ((numbytes = recv(sockfd, buf, sizeof (buf), 0)) == -1) {
//if ((numbytes = recv(new_fd, buf, sizeof (buf), MSG_WAITALL)) == -1) { // I THINK THE BETTER WAY IS to CHECK THE OUTPUT AND LOOP UNTIL COMPLETE.
lenRecv = sizeof (buf);
//if (recv_all(new_fd, (char *)buf, &lenRecv) == -1) {
if (recv_all(new_fd, buf, &lenRecv) == -1) {
perror("sendall");
printf("We only sent %d bytes because of the error!\n", lenRecv);
}
}
close(new_fd);
exit(0);
}
close(new_fd); // parent doesn't need this
}
return 0;
}
You are ignoring end of stream. If n == 0 the peer has disconnected. Your code will loop forever.
Throw it all away and use recv() with the MSG_WAITALL option.
give recv_all a timeout value
int recv_all(int socket, char *buffer, int *length, int timeout)
and use select before recv()
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
looks like this
int recv_all(int socket, char *buffer, int *length)
{
int total = 0; // how many bytes we've sent
int bytesleft = *length; // how many we have left to send
int n = -1;
struct timeval timeout;
fd_set rset;
int rc;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
while(total < *length) {
FD_ZERO(&rset);
FD_SET(socket, &rset);
rc = select(socket + 1, &rset, NULL, NULL, &timeout);
if(rc < 0)
{
// errno
n = -1;
break;
}
if(0 == rc)
{
// timeout
n = -1;
break;
}
if(FD_ISSET(socket, &rset))
{
n = recv(socket, buffer+total, bytesleft, 0);
if (n == -1) { break; }
total += n;
bytesleft -= n;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
}
}
*length = total; // return number actually received here
return n==-1?-1:0; // return -1 on failure, 0 on success
}

server can't send message to Client over Socket in C

Hi I'm writing 2 Programs (Server, Client) which should communicate with each other over sockets. The Client is able to send its first message to the server with no problem, but when the server tries to answer, the client receives just an empty msg: recv(...) is 0.
The server suddenly stops after the send(...) function is called.
Here is my Code:
Server:
/* Create a new TCP/IP socket `sockfd`, and set the SO_REUSEADDR
option for this socket. Then bind the socket to localhost:portno,
listen, and wait for new connections, which should be assigned to
`connfd`. Terminate the program in case of an error.
*/
struct sockaddr_in sin,
peer_addr;
//-----gen socket-----//
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
bail_out(EXIT_PARITY_ERROR, "could not create Socket");
//-----bind-----//
memset(&sin, 0, sizeof (sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(options.portno);
sin.sin_addr.s_addr = INADDR_ANY;
if (bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0)
bail_out(EXIT_PARITY_ERROR, "Failed to bind to Port");
//-----listen-----//
if (listen(sockfd, 5) < 0)
bail_out(EXIT_PARITY_ERROR, "Server can't accepted connection");
//-----accept-----//
int sock_len = sizeof peer_addr;
if ((connfd = accept(sockfd, (struct sockaddr*)&peer_addr, (socklen_t *)&sock_len)) < 0) //fragen
bail_out(EXIT_PARITY_ERROR, "Can't accept connection to Client");
/* accepted the connection */
//Some other Code which has nothing to do with my Error!
/* read from client (WORKS FINE!!)*/
if (read_from_client(connfd, &buffer[0], READ_BYTES) == NULL) {
if (quit) break; /* caught signal */
bail_out(EXIT_FAILURE, "read_from_client");
}
request = (buffer[1] << 8) | buffer[0];
DEBUG("Round %d: Received 0x%x\n", round, request);
/* compute answer */
correct_guesses = compute_answer(request, buffer, options.secret);
if (round == MAX_TRIES && correct_guesses != SLOTS) {
buffer[0] |= 1 << GAME_LOST_ERR_BIT;
}
DEBUG("Sending byte 0x%x\n", buffer[0]);
/* send message to client */
if (send_to_client(sockfd, &buffer[0], WRITE_BYTES) == NULL) { //Error in this Method!
if (quit) break; /* caught signal */
bail_out(EXIT_FAILURE, "can't send message!");
}
Methods:
static uint8_t *send_to_client(int fd, uint8_t *buffer, size_t n)
{
/* loop, as packet can arrive in several partial reads */
size_t bytes_send = 0;
do {
ssize_t r = send(fd, buffer + bytes_send, n - bytes_send, 0); //Program stops HERE!
printf("%d\n", (int)r); //This and the following lines will not be executed!
if (r <= 0) {
return NULL;
}
bytes_send += r;
} while (bytes_send < n);
if (bytes_send < n) {
return NULL;
}
return buffer;
}
Client: (Might be usefull)
sockfd = cnt_to_server(argv[1], argv[2]);
uint8_t buffer;
uint16_t msg_buffer;
do
{
msg_buffer = generate_msg(&msg);
printf("Sending byte 0x%x\n", msg_buffer);
if (send_to_server(sockfd, &msg_buffer, WRITE_BYTES) == NULL) //works
error_exit(EXIT_FAILURE, "can't send message!");
if (read_from_server(sockfd, &buffer, READ_BYTES) == NULL) //NULL
error_exit(EXIT_FAILURE, "can't read message!");
printf("received byte 0x%x\n", buffer);
} while (game_continue(buffer, &msg));
(void)close(sockfd);
Methods:
uint8_t* read_from_server(int fd, uint8_t *buffer, int n)
{
/* loop, as packet can arrive in several partial reads */
size_t bytes_recv = 0;
do {
ssize_t r;
r = recv(fd, buffer + bytes_recv, n - bytes_recv, 0); //0
printf("%d\n", (int)r);
if (r <= 0) {
return NULL;
}
bytes_recv += r;
} while (bytes_recv < n);
if (bytes_recv < n) {
return NULL;
}
return buffer;
}
int cnt_to_server(const char *par_server, const char *par_port)
{
struct sockaddr_in server;
struct hostent *hp;
int sockfd;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
error_exit(EXIT_FAILURE, "could not create Socket");
server.sin_family = AF_INET;
if ((hp = gethostbyname(par_server)) == 0)
error_exit(EXIT_FAILURE, "host error!");
memcpy(&server.sin_addr, hp->h_addr, hp->h_length);
server.sin_port = htons(parse_port(par_port));
if (connect(sockfd, (struct sockaddr*) &server, sizeof server) < 0)
error_exit(EXIT_FAILURE, "could not connect!");
return sockfd;
}
Thx for helping me out with this!
Change
if (send_to_client(sockfd, &buffer[0], WRITE_BYTES) == NULL)
to
if (send_to_client(connfd, &buffer[0], WRITE_BYTES) == NULL)
The solution is to use connfd (File descriptor for connection socket) instead of sockfd:
/* read from client */
if (read_from_client(connfd, &buffer[0], READ_BYTES) == NULL) {
if (quit) break; /* caught signal */
bail_out(EXIT_FAILURE, "read_from_client");
}

Socket addresing mechanism stuck

Basically i'm trying to do a server-client program that communicates with sockets.
I find it strange that the server, once started it doesn't even print the first line. Why is this?
There must be something that's sliping from me and I really need to know what.
Server.c
int rvsock;
void stop(int sig){
close(rvsock);
}
void* worker(void* p){
struct mymsg m;
int err;
int sock = (int)p;
err = recv(sock,&m,sizeof(m),0);
if(err < 0){
printf("Failed to receive");
exit(1);
}
m.a = ntohl(m.a);
m.b = ntohl(m.b);
m.c = ntohl(m.c);
m.ip = ntohl(m.ip);
printf("Received numbers: %d %d %d from IP:%d", m.a,m.b,m.c,m.ip);
if(m.a < m.b && m.b <= m.c)
m.a = m.c;
else if(m.a < m.b && m.b >= m.c)
m.a = m.b;
else if(m.a > m.b && m.b <= m.c)
m.a = m.a;
m.a = htonl(m.a);
m.b = htonl(m.b);
m.c = htonl(m.c);
err = send(sock, &m,sizeof(m),0);
if(err < 0){
printf("Failed to send!");
close(sock);
return NULL;
}
close(sock);
return NULL;
}
int main(int argc, char** argv) {
printf("DAFUQ"); //It doesn't even print this. Why?
int port;
int sock;
int err;
unsigned int len;
struct sockaddr_in saddr;
struct sockaddr_in caddr;
pthread_t w[100];
int wn = 0;
int i;
sscanf(argv[1], "%d", &port);
signal(SIGINT, stop);
rvsock = socket(AF_INET, SOCK_STREAM, 0);
if(rvsock < 0) {
perror("Failed to create socket");
exit(1);
}
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = INADDR_ANY;
saddr.sin_port = htons(port);
err = bind(rvsock, (struct sockaddr*)&saddr,
sizeof(struct sockaddr_in));
if(err < 0) {
perror("Failed to bind");
exit(1);
}
err = listen(rvsock, 5);
if(err < 0) {
perror("Failed to listen");
close(rvsock);
exit(1);
}
while(1) {
len = sizeof(struct sockaddr_in);
sock = accept(rvsock, (struct sockaddr*)&caddr, &len);
if(sock < 0) {
perror("Failed to accept");
break;
}
pthread_create(&w[wn], 0, worker, (int*)sock);
wn++;
}
for(i=0; i<wn; i++) {
pthread_join(w[i], 0);
}
return 0;
}
client.c
int main(int argc, char** argv){
int sock;
int err;
int port;
struct sockaddr_in saddr;
struct mymsg m;
sscanf(argv[1], "%d", &port);
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0){
printf("failed to create");
exit(1);
}
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
saddr.sin_port = htons(port);
err = connect(sock, (struct sockaddr*)&saddr, sizeof(struct sockaddr_in));
if(err < 0){
perror("Failed to connect!");
exit(1);
}
printf("give a:");scanf("%d",&m.a);
printf("give b:");scanf("%d",&m.b);
printf("give c:");scanf("%d",&m.c);
m.a = htonl(m.a);
m.b = htonl(m.b);
m.c = htonl(m.c);
send(sock,&m,sizeof(m),0);
return 0;
}
message.h
struct mymsg{
int a;
int b;
int c;
int ip;
};
In your server you have this line. printf prints to the stdout FILE which is opened for you when you start your program.
printf("DAFUQ"); //It doesn't even print this. Why?
man stdout provides the following information about stdout:
The stream stdout is line-buffered
when it points to a terminal. Partial lines will not appear until
fflush(3) or exit(3) is called, or a newline is printed.
You don't print a newline, you don't flush stdout and your program doesn't exit, therefore none of the conditions required to print your output to the terminal are met.
Therefore in order to print the line you have 3 options:
1
printf("DAFUQ"); //It doesn't even print this. Why?
fflush(stdout);
2
printf("DAFUQ\n"); /*notice added '\n'*/
3
call exit() after you print ( not very helpful probably).

Resources