I wrote a server program and a client program that communicate with sockets on linux ubuntu. The client program outputs Received: 艎��
This my server code:
/*** tcp_server.c ***/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main() {
int sock_fd, new_fd, bytes;
struct sockaddr_in seraddr, cliaddr;
char data[1024];
socklen_t cli_addr_size;
cli_addr_size = sizeof(cliaddr);
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
memset(&seraddr, 0, sizeof(seraddr));
seraddr.sin_family = AF_INET;
seraddr.sin_addr.s_addr = htonl(INADDR_ANY); // INADDR_ANY : It received Network Interface that connected server defined interface, htonl :
seraddr.sin_port = htons(5050);
bind(sock_fd, (struct sockaddr *)&seraddr, sizeof(seraddr));
listen(sock_fd, 10);
while (1) {
new_fd = accept(sock_fd, (struct sockaddr *)&cliaddr, &cli_addr_size);
bytes = recv(new_fd, data, 1024, 0);
send(new_fd, data, bytes, 0);
close(new_fd);
}
close(sock_fd);
}
My client code is:
/*** tcp_client.c ***/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main(int argc, char *argv[]) {
int sock_fd, bytes;
struct sockaddr_in ser_addr;
char *snddata, rcvdata[1024];
snddata = argv[2];
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
memset(&ser_addr, 0,sizeof(ser_addr));
ser_addr.sin_family = AF_INET;
ser_addr.sin_addr.s_addr = inet_addr(argv[1]); // INADDR_ANY : It received Network Interface that connected server defined interface, htonl :
ser_addr.sin_port = htons(5050);
connect(sock_fd, (struct sockaddr *)&ser_addr, sizeof(ser_addr));
send(sock_fd, snddata, strlen(snddata), 0);
printf("Received: ");
bytes = recv(sock_fd, rcvdata, 1024, 0);
rcvdata[bytes] = '\0';
printf("%s\n", rcvdata);
close(sock_fd);
}
First I got an error for argument 3 of accept, then I changed
new_fd = accept(sock_fd, (struct sockaddr *)&cliaddr, sizeof(cliaddr);
But It still produces this strange word.
Try to change your send() and receive() functions so that you have full control over how much and which byte you send from the buffer (data[1024]) like in this thread : C socket: recv and send all data and also see Beej's Guide to Network Programming (http://beej.us/guide/bgnet/)
Also make sure that you initialize your data buffers:
data[1024] = "";
rcvdata[1024] = "";
or
data[1024];
data[0] = '\0';
rcvdata[1024];
rcvdata[0] = '\0';
, background is in this thread : Why I am getting this unusually symbols by printing char string
Related
I'm trying to learn UDP on C.
My goal is to send a message in console, in the client consol to the server, and sending the exact same message from the server to the client.
When I send a message from client to server, I do receive it, but the opposit is not working, and the waiting is infinite.
I don't have any problem in console.
The weird thing is that i'm using the exact same methode to send both messages.
Here's my client, Thanks to everyone helping me :)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define BUFSIZE 4096
// Driver code
int main(int argc, char *argv[]) {
char buffer[BUFSIZE];
struct sockaddr_in servaddr, cliaddr;
int len, n;
char *adresse= argv[1];
if (argc<1){
perror("nb args not enough");
exit(EXIT_FAILURE);
}
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(adresse);
servaddr.sin_port = htons(PORT);
// Socket()
int udp_server = socket(AF_INET, SOCK_DGRAM, 0) ;
if(udp_server<0){
perror("socket creation failed \n");
exit(EXIT_FAILURE);
}
// Bind())
int errBind = bind(udp_server, (const struct sockaddr *)&servaddr, sizeof(servaddr));
if(errBind<0){
perror("errBind \n" );
exit(EXIT_FAILURE);
}
// recvfrom()
n = recvfrom(udp_server, (char *)buffer, BUFSIZE,0, ( struct sockaddr *) &cliaddr,&len);
if (n<0){
perror("recvfrom error\n" );
exit(EXIT_FAILURE);
}
buffer[n] = '\0';
printf("CLIENT: %s\n", buffer);
char *message ="caca";
sendto(udp_server, (const char *)message, strlen(message),
0, (const struct sockaddr *) &cliaddr,
len);
close(udp_server);
//////////////////////////This part below is never reached
printf("end");
return 0;
}
Also here's my server:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define BUFSIZE 4096
// Driver code
int main(int argc, char *argv[]) {
char buffer[BUFSIZE];
// char *message = "AAAAAAAAAAAAAAAAAA";
struct sockaddr_in servaddr, cliaddr;
int len, n;
char *adresse= argv[1];
if (argc<1){
perror("nombre d'arguments insuffisents, veuillez entrer :\n ./serveur port_serveur \n");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(adresse);
// servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// Socket()
int udp_server = socket(AF_INET, SOCK_DGRAM, 0) ;
if(udp_server<0){
perror("socket creation failed \n");
exit(EXIT_FAILURE);
}
// Bind())
int errBind = bind(udp_server, (const struct sockaddr *)&servaddr, sizeof(servaddr));
if(errBind<0){
perror("errBind \n" );
exit(EXIT_FAILURE);
}
// recvfrom()
n = recvfrom(udp_server, (char *)buffer, BUFSIZE,0, ( struct sockaddr *) &cliaddr,&len);
if (n<0){
perror("recvfrom error\n" );
exit(EXIT_FAILURE);
}
buffer[n] = '\0';
printf("CLIENT: %s\n", buffer);
int l = sendto(udp_server, (const char *)buffer, strlen(buffer),
0, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
close(udp_server);
printf("end");
//////////////// This is reached
return 0;
}
There are several issues. The main issue is that both the client and server first tries to receive, then send. Thus they cannot both receive the message from the other party. Also, the client need not explicitly bind the socket.
In principle, the client must know the server address, but the server does not know the client address. Hence, the flow of communication must be that the client first sends a message to the server which will make the client known to the server. The server can then send a message to the address of the client.
In summary, the server should:
Create socket
Bind socket
Wait for message (recvfrom())
Send message to sender of the received message (sendto())
Close socket
The client should:
Create socket
Send message to the server (sendto())
Wait for message (recvfrom())
Close socket
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char *argv[]){
// established the socket
char inputBuffer[256] = {};
char message[] = {"Hi this is the server.\n"};
int sockfd = 0;
int forClientSocketfd = 0;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1) printf("Fail to create the socket.");
// socket connection
struct sockaddr_in serverInfo, clientInfo;
int addrlen = sizeof(clientInfo);
bzero(&serverInfo, sizeof(serverInfo));
serverInfo.sin_family = PF_INET;
serverInfo.sin_addr.s_addr = INADDR_ANY;
serverInfo.sin_port = htron(10024);
bind(sockfd, (struct sockaddr *) &serverInfo, sizeof(serverInfo));
listen(sockfd, 5);
while(1){
forClientSocketfd = accept(sockfd, (struct sockaddr*) &clientInfo, &addrlen);
send(forClientSocketfd, message, sizeof(message), 0);
recv(forClientSocketfd, inputBuffer, sizeof(inputBuffer), 0);
printf("Received from client: %s\n", inputBuffer);
}
return 0;
}
This is the code for socket programming that I seen through from the net. when I compiled it, it throw the error message as below. Having no idea what's going on, even though searching through the internet. p.s. Client operate as normal.
enter image description here
you have a typo on line number 24 it should be htons and not htron
htons()
The htons function takes a 16-bit number in host byte order and returns a 16-bit number in network byte order used in TCP/IP networks(the AF_INET or AF_INET6 address family). The htons function can be used to convert an IP port number in host byte order to the IP port number in network byte order
also add the stdio header file to your code to remove the other warnings
heres the final corrected code with no warnings or errors.
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
// established the socket
char inputBuffer[256] = {};
char message[] = {"Hi this is the server.\n"};
int sockfd = 0;
int forClientSocketfd = 0;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
printf("Fail to create the socket.");
// socket connection
struct sockaddr_in serverInfo, clientInfo;
int addrlen = sizeof(clientInfo);
bzero(&serverInfo, sizeof(serverInfo));
serverInfo.sin_family = PF_INET;
serverInfo.sin_addr.s_addr = INADDR_ANY;
serverInfo.sin_port = htons(10024);
bind(sockfd, (struct sockaddr *)&serverInfo, sizeof(serverInfo));
listen(sockfd, 5);
while (1)
{
forClientSocketfd = accept(sockfd, (struct sockaddr *)&clientInfo, &addrlen);
send(forClientSocketfd, message, sizeof(message), 0);
recv(forClientSocketfd, inputBuffer, sizeof(inputBuffer), 0);
printf("Received from client: %s\n", inputBuffer);
}
return 0;
}
I'm trying to complete a simple echo server. The goal is to repeat back the message to the client. The server and client both compile. The server runs, you just need to give it a port to run on. The client has the address, the port, and the message. When the client goes through the program to the sendto section, it stop and waits there. My goal it to have it sent to the server, and the server to send it back.
I believe that the server works, or it least is in the mode to receive as it enters the while loops to do that. That part can send notes back that it works.
For the client, I've tried sending the argument directly, but also through a c-string. I've tried one hard coded in, and none of them have worked. I've been at it for many hours, so I decided to ask for help because I can't think of anything else as a newbie.
Client
//argv[1] address, argv[2] port, argv[3] message
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
int main(int argc, char *argv[]){
int BUF_LEN;
for (BUF_LEN = 0; argv[3][BUF_LEN] != '\0'; BUF_LEN++){
// printf("BUF_LEN = %i\n", BUF_LEN);
}
int s, n, port_no, r;
struct sockaddr_in server_addr;
char *haddr, *message;
char buf[BUF_LEN+1];
printf("Variables created\n");
s = socket(AF_INET, SOCK_DGRAM, 0); // create a socket for UDP
printf("Socket created as s: %i\n", s);
bzero((char *)&server_addr, sizeof(server_addr)); // clear
server_addr.sin_family = AF_INET; //IPv4 Internet family
server_addr.sin_addr.s_addr = inet_addr(argv[1]); //server address
server_addr.sin_port = htons(atoi(argv[2])); // server port number
printf("Server addr complete\n");
//Bind() - Not necessary
printf("Bind skipped\n");
//sendto()
r = sendto(s, argv[3], strlen(argv[3]), 0, (struct sockaddr *)&server_addr, BUF_LEN);
printf("Message Sent");
//recvfrom()
n = recvfrom (s, buf, BUF_LEN, 0, (struct sockaddr *)&server_addr, &BUF_LEN);
printf("Message Received: %s\n", buf);
close(s);
}
Server
//Argv[1] : port number
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
int main(int argc, char *argv[]){
int n;
int MAXLINE = 512;
int sock_server, sock_client, r, len;
char buf[MAXLINE];
struct sockaddr_in my_addr, client_addr;
//printf("Variables created\n");
sock_server = socket (PF_INET, SOCK_DGRAM, 0);
//printf("Socket created\n");
if (sock_server < 0){
perror("Bind failed");
exit(1);
}
bzero(&my_addr, sizeof(my_addr)); // clear
my_addr.sin_family = AF_INET; //Address Family INET
my_addr.sin_port = htons(atoi(argv[1])); //Server port number
my_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Accept from anywhere
//printf("Addresses created\n");
r = bind(sock_server, (struct sockaddr*)(&my_addr), sizeof(my_addr));
if (r < 0) {
perror("Bind failed");
exit(1);
}
printf("Read to receive\n");
while(1) {
//printf("First while loop\n");
len = sizeof(struct sockaddr_in);
//recvfrom()
n = recvfrom (sock_client, buf, MAXLINE, 0, (struct sockaddr *)&client_addr, &len);
while (n > 1){
printf("Second while loop\n");
printf("Message Received: %s\n", buf);
//sendto()
sendto(sock_client, buf, n, 0, (struct sockaddr *)&client_addr, len);
n = 0;
}
}
close(sock_client); //close the client socket
//printf("Connection sock_client Closed");
}
Here is the fixed version of the client using sizeof(server_addr) in the client call of sendto:
//argv[1] address, argv[2] port, argv[3] message
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
int main(int argc, char *argv[]){
int BUF_LEN;
for (BUF_LEN = 0; argv[3][BUF_LEN] != '\0'; BUF_LEN++){
// printf("BUF_LEN = %i\n", BUF_LEN);
}
int s, n, port_no, r;
struct sockaddr_in server_addr;
char *haddr, *message;
char buf[BUF_LEN+1];
printf("Variables created\n");
s = socket(AF_INET, SOCK_DGRAM, 0); // create a socket for UDP
printf("Socket created as s: %i\n", s);
bzero((char *)&server_addr, sizeof(server_addr)); // clear
server_addr.sin_family = AF_INET; //IPv4 Internet family
server_addr.sin_addr.s_addr = inet_addr(argv[1]); //server address
server_addr.sin_port = htons(atoi(argv[2])); // server port number
printf("Server addr complete\n");
//Bind() - Not necessary
printf("Bind skipped\n");
r = sendto(s, argv[3], strlen(argv[3]), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
printf("Message Sent");
n = recvfrom (s, buf, BUF_LEN, 0, (struct sockaddr *)&server_addr, &BUF_LEN);
printf("Message Received: %s\n", buf);
close(s);
}
Problem:
I need some help with an error in my code. The chat client works when I only have one client running but if i use more clients. Only the last client messages will show up on my server. my client.c seems to work since it is sending but for some reason recv() is not getting the previous client send().
How code works:
I set up my server and spawn a new thread whenever a new client connects. the thread will handle the messages i get form the client and print it on the server screen.
Code:
CLIENT.C
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <netdb.h>
#include <unistd.h>
#include <signal.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int main(int argc, char ** argv){
//get port
//int port = atoi(argv[1]);
int server_port = atoi(argv[1]);
char * name =argv[2];
int namelength = strlen(name);
//set up server adress and socket
int sock = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(server_port);
//connect
if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
perror("connect failed");
exit(1);
}
//set up client name
char * buff = malloc(5000*sizeof(char));
//get the chatting
//char * other_message = malloc(5000*sizeof(char));
while(1){
printf("ENTER MESSAGE:\n");
char message[5000];
strcpy(message, name);
strcat(message,": ");
printf("%s", message);
scanf("%[^\n]",buff);
getchar();
strcat(message,buff);
int sent = send(sock , message , strlen(message) , MSG_DONTWAIT );
if (sent == -1)
perror("Send error: ");
else
printf("Sent bytes: %d\n", sent);
}
return 0;
}
SERVER.C
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <netdb.h>
#include <unistd.h>
#include <signal.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
pthread_t * threads = NULL;
int * client_fd = NULL;
int num_clients;
int thread_num;
void * client_handler(void * cl)
{
int * client = (int *)cl;
char * message = malloc(5000*sizeof(char));
printf("Connected: %d\n",*client);
int byte=1;
//recieve the message from clients
while(1)
{
byte=recv(*client, message , 5000 , 0);
if(byte< 0)
break;
//send message to all other clients
printf("%s\n",message);
printf("Recieved bytes:%d\n",byte);
memset(message, 0, 5000);
/*for(i=0;i<num_clients;i++)
if(client_fd[i]!=*client)
send(*client , message , strlen(message),0);*/
}
printf("finished: %d\n",*client);
return NULL;
}
int main(int argc, char ** argv)
{
//get the port
int port = atoi(argv[1]);
//set up socket
int socket_fd = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in server,client;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(port);
//bind
if(bind(socket_fd, (struct sockaddr*)&server,sizeof(server)) < 0 ){
perror("binding error\n");
exit(1);
}
//listen
if( listen(socket_fd, 10) <0){
perror("binding error\n");
exit(1);
}
//accept incoming connectionns
threads = malloc(10*sizeof(pthread_t));
client_fd = malloc(10*sizeof(int));
int i=0;
int c = sizeof(struct sockaddr_in);
while(1)
{
int c_fd = accept(socket_fd,(struct sockaddr *)&client, (socklen_t*)&c);
if(c_fd < 0)
printf("error");
client_fd[i]=c_fd;
pthread_create(&threads[i],NULL,client_handler,(void *)(&c_fd));
i++;
num_clients=i;
}
return 0;
}
Sending C-style strings with strlen(). Does not send the terminating null. Use strlen()+1
Ignoring the value returned by recv(). TCP is a streaming protocol that only transfers bytes/octets. It does not transfer anything more complex. recv() may return one byte of your chat line, all of your chat line, or anything in between. To transfer any message more complex than one byte, you need a protocol and you must handle it. Yours is 'chat lines are null-terminated strings', so you need to call recv() in a loop and, using the returned value, concatenate the bytes received until the null arrives.
Trying to printf non-strings with "%s". You must not attempt to print out the received data until you are sure that a null has been received.
I am working on a server/client program for a project, for it to be able to work properly I need to use fopen and fprintf on the client. The server is going to take realtime data output from a USB joystick (the axis rotations) and send that information via TCP to the client which in turn writes that information to a file. I have followed THIS tutorial to get the TCP setup and its working perfectly. I am able to send messages from the server to the client. How can I take a command such as fprintf(fp, "2=%d\n", zAxis) from the server and send it to the client to be wrote to a file? Maybe I am overlooking something simple to accomplish this. I don't know where to begin, if I can send the zAxis variable from the server to the client I think I can figure it out from there.
Here is my code
SERVER.C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define PORTNUM 2343
int main(int argc, char *argv[])
{
char msg1[10];
printf("Please enter info\n");
fgets(msg1, 20, stdin);
struct sockaddr_in dest; /* socket info about the machine connecting to us */
struct sockaddr_in serv; /* socket info about our server */
int mysocket; /* socket used to listen for incoming connections */
socklen_t socksize = sizeof(struct sockaddr_in);
memset(&serv, 0, sizeof(serv)); /* zero the struct before filling the fields */
serv.sin_family = AF_INET; /* set the type of connection to TCP/IP */
serv.sin_addr.s_addr = htonl(INADDR_ANY); /* set our address to any interface */
serv.sin_port = htons(PORTNUM); /* set the server port number */
mysocket = socket(AF_INET, SOCK_STREAM, 0);
/* bind serv information to mysocket */
bind(mysocket, (struct sockaddr *)&serv, sizeof(struct sockaddr));
/* start listening, allowing a queue of up to 1 pending connection */
listen(mysocket, 1);
int consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
while(consocket)
{
printf("Incoming connection from %s - sending welcome\n", inet_ntoa(dest.sin_addr));
send(consocket, msg1, strlen(msg1), 0);
consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
}
close(consocket);
close(mysocket);
return EXIT_SUCCESS;
}`
CLIENT.C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define MAXRCVLEN 500
#define PORTNUM 2343
int main(int argc, char *argv[])
{
char buffer[MAXRCVLEN + 1]; /* +1 so we can add null terminator */
int len, mysocket;
struct sockaddr_in dest;
mysocket = socket(AF_INET, SOCK_STREAM, 0);
memset(&dest, 0, sizeof(dest)); /* zero the struct */
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr("192.168.254.16"); /* set destination IP number */
dest.sin_port = htons(PORTNUM); /* set destination port number */
connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr));
len = recv(mysocket, buffer, MAXRCVLEN, 0);
/* We have to null terminate the received data ourselves */
buffer[len] = '\0';
printf("Received %s (%d bytes).\n", buffer, len);
close(mysocket);
return EXIT_SUCCESS;
}