What's the data transformation pattern of when using tcp socket? - c

I have two server codes:
the first server: send the client a char each time until the string is finished
int
main(int argc, char **argv)
{
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[MAXLINE];
time_t ticks;
char temp[1];
int i = 0;
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(9999); /* daytime server */
Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
Listen(listenfd, LISTENQ);
for ( ; ; ) {
connfd = Accept(listenfd, (SA *) NULL, NULL);
ticks = time(NULL);
snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
for(i = 0; i < strlen(buff); i++)
{
temp[0] = buff[i];
Write(connfd, temp, strlen(temp));
}
Close(connfd);
}
}
the second server: send the client a string
int
main(int argc, char **argv)
{
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[MAXLINE];
time_t ticks;
char temp[1];
int i = 0;
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(9999); /* daytime server */
Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
Listen(listenfd, LISTENQ);
for ( ; ; ) {
connfd = Accept(listenfd, (SA *) NULL, NULL);
ticks = time(NULL);
snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
Write(connfd, buff, strlen(buff));
Close(connfd);
}
}
the client:receive the chars sent by the server
int
main(int argc, char **argv)
{
int sockfd, n;
char recvline[MAXLINE + 1];
struct sockaddr_in servaddr;
int count = 0;
if (argc != 2)
err_quit("usage: a.out <IPaddress>");
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
err_sys("socket error");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(9999); /* daytime server */
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0)
err_quit("inet_pton error for %s", argv[1]);
if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)
err_sys("connect error");
while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {
recvline[n] = 0; /* null terminate */
count++;
if (fputs(recvline, stdout) == EOF)
err_sys("fputs error");
}
if (n < 0)
err_sys("read error");
printf("read time:%d\n", count);
exit(0);
}
the result is both of the output of variable count is 1. My question is why the first server's output is 1, I think the result should be strlen(buff) for the 1st server?
PS:I run the server and client on the same machine.

TCP is a stream protocol. As such the number of writes on one side will not cause the same amount of reads on the other side since the protocol doesn't preserve information about how the writes into the socket were made.
Usually, on the sender side there's a delay before a packet is sent in case you write more data to the socket so that more data can be stuffed into the same packet. One of the reasons for it is that a badly written server might flood the network with single byte packets.
On the receiver side, the protocol doesn't know why your data might have arrived as separate packets, it might have been split up because of the MTU, it might have been reassembled by some packet inspection software or appliance on the way, so whenever you read from your socket it will give you as much data as it can regardless of how it was sent to you.
On a local machine like in your setup it's likely that the client isn't even running while the server is writing, so even without buffering on the sender side it will not start reading until the server has written everything and therefore it will read everything in one go. Or not, you might be unlucky, your server gets preempted for long enough that the TCP implementation in your kernel thinks that there won't be any more data you'll be sending, send a single byte to the client, the client gets scheduled to run before the server runs again and the client will receive just one byte in the first read.

Related

C Sockets - send() sends, recv() not receiving

So I'm doing some client server stuff here, and I want my server to listen for clients, and when a client connects to the server, the client sends a string.
The connection establishes, the clients sends it's string, but, at server side, recv() returns -1.
/* Server */
int main() {
int fd, conn_fd;
struct sockaddr_in ad;
int bytes;
char recv_buffer[256];
fd = socket(AF_INET, SOCK_STREAM, 0);
ad.sin_family = AF_INET;
ad.sin_port = htons(3335);
ad.sin_addr.s_addr = htonl(INADDR_ANY);
bind(fd, (struct sockaddr*)&ad, sizeof(ad));
listen(fd, 5);
conn_fd = accept(fd, (struct sockaddr*)0, 0);
bytes = recv(fd, recv_buffer, sizeof(recv_buffer), 0);
printf("%d\n", bytes);
return 0;
}
The clients simply connects to the server:
/* Client */
int main() {
int fd, n;
unsigned int s;
struct sockaddr_in addr;
fd = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
addr.sin_port = htons(3335);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
char buff[256] = "time";
printf("Connecting to server....\n");
if(connect(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
printf("connect() error.\n");
exit(1);
}
s = send(fd, buff, sizeof(buff), 0);
return 0;
}
Thanks!
I found out what the problem was. In my server code, I was using the wrong socket descriptor for recv(): instead of fd, I should have used conn_fd.

first client request not being served in sockets in c

This is a simple iterative client-server program. Where the server prints out "Received request" on successful establishment of connection.
server side
#define LENGTH 256
#define SERV_PORT 4000
#define LISTENQ 8
int main()
{
int listenfd, connfd, n;
socklen_t clilen;
char buf[LENGTH];
struct sockaddr_in cliaddr, servaddr;
//creation of socket
listenfd = socket (AF_INET, SOCK_STREAM, 0);
//creating socket address
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
bind (listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
// printf("\nServer running.. waiting for connections");
// listen(listenfd, LISTENQ);
for(; ;)
{
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);
printf("\nReceived request");
//sleep(5);
}
return 0;
}
client side
#define LENGTH 256
#define SERV_PORT 4000
int main( int argc, char *argv[])
{
int sock;
struct sockaddr_in server;
struct hostent *hp;
char buff[256];
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
perror("socket failed");
exit(1);
}
server.sin_family = AF_INET;
hp = gethostbyname(argv[1]);
if(hp == 0)
{
perror("gethost by name failed");
exit(1);
}
memcpy(&server.sin_addr, hp->h_addr, hp->h_length);
server.sin_port = htons(4000);
if(connect(sock, (struct sockaddr *) &server, sizeof(server)) < 0)
{
perror("\nconnect failed");
exit(1);
}
return 0;
}
When I run this multiple client-server code, the output for first client is different from the preceding clients. I need the first client to output like others. Can someone help?
When the first client establishes a connection with the server, the server doesn't output "Received request", where as, for the other clients do output "Received request".
You need to restore the listen() call. – EJP

Client same socket descriptors

I have a server-client system (concurrent server). I have different clients on different machines. I am trying to send a notification to particular clients. However, I have a problem as the clients all have the same socket descriptor. On both computers, the clients have a socket descriptor of 3 and at the server a sd of 5. Can someone please tell me how I can identify these different clients and why is this happening?
int main(int argc, char *argv[]) {
pid_t pid;
int buff_size = 1024;
char buff[buff_size];
int listen_fd, client_conn;
struct sockaddr_in serv_addr;
int server_port = 5001;
char remote_file[255];
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) {
perror("Socket cannot be opened");
exit(1);
}
/*Turning off address checking in order to allow port numbers to be
reused before the TIME_WAIT. Otherwise it will not be possible to bind
in a very short time after the server has been shut down*/
int on = 1;
int status = setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR,
(const char *) &on, sizeof(on));
if (status == -1) {
perror("Failed to Reuse Address on Binding");
}
// Initialise socket structure
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY; // Accept connections from any address
serv_addr.sin_port = htons(server_port);
// Bind the host address
if (bind(listen_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))
< 0) {
perror("ERROR on binding");
exit(1);
}
// Start listening for the clients, here process will
// go in sleep mode and will wait for the incoming connection
listen(listen_fd, 5);
while (1) {
//Accepting client connection
client_conn = accept(listen_fd, (struct sockaddr *) NULL, NULL);
if (client_conn < 0) {
perror("Client was not accepted...");
exit(1);
}
if ((pid = fork()) == 0) {
close(listen_fd);
bzero(buff, buff_size);
while ((bytes_read = read(client_conn, buff, buff_size)) > 0) {
fclose(file);
}
}
//Terminating child process and closing socket
close(client_conn);
exit(0);
bzero(buff, buff_size);
}
//parent process closing socket connection
close(client_conn);
}
return 0;
}
After the server forks a child it does close(client_conn). When accept assigns a socket descriptor to the new connection, it uses the lowest closed descriptor. Since you closed the socket earlier, it can be used for the next client that comes in.
This isn't a problem, because the connections are being managed by the child processes. They each have their own descriptor 5, and they don't interfere with each other.
You can get the client address & port returned to you by accept. Currently you are passing a null
client_conn = accept(listen_fd, (struct sockaddr *) NULL, NULL);
however just add a few lines like
struct sockaddr_in serv_addr, cli_addr;
int len = sizeof(cli_addr);
client_conn = accept(listen_fd, (struct sockaddr *) &cli_addr, &len);
and you have the client info in cli_addr.sin_addr.s_addr and cli_addr.sin_port.
You can get the pid of the child processing the connection from the return code of fork. That should give you all the information you need to create a table.

Segmentation fault trying to send message to client from server

I need to send a message to a client and then the client have to respond with an option. I get till the client and server connects, but both program end with "Segmentation Fault". Does anyone knows what this error means? Can someone give an idea to how to create a code that will make client and server interact. After receiving the option chosen by the client the server have to analyze it and send again a result to client.
My codes are:
Server
int
main(int argc, char **argv)
{
int listenfd, connfd;
socklen_t len;
struct sockaddr_in servaddr, cliaddr;
char buff[MAXLINE];
time_t ticks;
char message[MAXLINE]="This is the server";
char temp_scale[2];
char recvdata[MAXLINE + 1];
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);/*----------------------------------------------------*/
servaddr.sin_port = htons(5555);
Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
Listen(listenfd, LISTENQ);
for ( ; ; )
{
len = sizeof(cliaddr);
connfd = Accept(listenfd, (SA *) &cliaddr, &len);
printf("Connection from %s, port %d\n",
Inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)),
ntohs(cliaddr.sin_port));
snprintf(message, sizeof(message), "%s\r\n");
Writen(connfd, message, strlen(message));
while ( (n = read(connfd, recvdata, MAXLINE)) > 0)
{
recvdata[n] = 0; /* null terminate*/
if (fputs(recvdata, stdout) == EOF)
err_sys("fputs error");
}
if (n < 0)
err_sys("read error");
Close(connfd);
}
}
Client
int
main(int argc, char **argv)
{
int sockfd, rd;
socklen_t len;
char recvline[MAXLINE + 1];
struct sockaddr_in servaddr, cliaddr;
char scale[2];
/*if (argc != 2)
err_quit("usage: a.out <IPaddress>");*/
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
err_sys("socket error");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(atoi(argv[2])); /*port passed through command line*/
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) /*The client translates the server address, passed on the command line*/
err_quit("inet_pton error for %s", argv[1]);
if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)
err_sys("connect error");
len = sizeof(cliaddr);
Getsockname(sockfd, (SA *) &cliaddr, &len);
printf("Local Address is: %s\n",
Sock_ntop((SA *) &cliaddr, sizeof(cliaddr)));
printf("Iniciando read...\n");
while ( (rd = read(sockfd, recvline, MAXLINE)) > 0)
{
recvline[rd] = 0; /* null terminate*/
if (fputs(recvline, stdout) == EOF)
err_sys("fputs error");
}
if (rd < 0)
err_sys("read error");
printf("Enter option 'A' or 'B'");
send_scale(sockfd);
exit(0);
}
Thanks
Your server is probably faulting because of this:
snprintf(message, sizeof(message), "%s\r\n"); // <== no parameters
It is flat-out wrong. The snprintf() call has a format specifier that is expecting a char * to a null-terminated string, and you're passing it absolutely nothing. It is therefore grabbing a random value out of the stack, treating it as a pointer, and dereferencing it in attempt to fulfill the formatted request.
Without knowing the details of the API you're using (it clearly isn't standard BSD sockets just by the names alone) there isn't much more to go on.
Run your code in a debugger (for example gdb ./a.out) and find out in no time.
I don't know if it might help, but in C the null termination for strings is '\0', when you print your response:
recvdata[n] = 0; /* null terminate ----> this must be '\0'*/
if (fputs(recvdata, stdout) == EOF)
err_sys("fputs error");
you pad it whith a "0", so it will probably lead you to a segfault when fputs parse your string in order to print it.
Hope it helps!

Sending multiple messages via send() recv(), Socket programming, C

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 :)
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);
The problem is that you're closing the listening socket sock, instead of the client socket clisock.
servaddr.sin_addr.s_addr = inet_addr(<ip_address_of_server>);
instead of the above lines in your client code use the following
inet_pton(AF_INET,"<ipofserver>",&servaddr.sin_addr);
perform an error check for the fllowing function also.

Resources