I am using Ubuntu 12.05.I have been trying to implement Stop and wait protocol through C socket programming.I have created two programs,one featuring the server and other one the client. Expected working of the code is explained through comments
serversocket.c
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <error.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
int main(int argc,char *argv[])
{
int listenfd = 0,qlength=10,connfd = 0,t=5;
int n;
struct sockaddr_in serv;
struct sockaddr_in dest;
socklen_t socksize = sizeof(struct sockaddr_in);
char sendBuff[1024]="hi\n";
//time_t ticks;
listenfd = socket(AF_INET,SOCK_STREAM,0); //socket for listening to connection requests
memset(&serv,'0',sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY);
serv.sin_port=htons(5000);
bind(listenfd,(struct sockaddr *)&serv,sizeof(serv)); //binding the socket to a port
listen(listenfd,2);
connfd=accept(listenfd,(struct sockaddr *)&dest,&socksize); //another socket for sending and receiving on the previously built socket
while(connfd){
printf("Incoming connection from %s-sending a hi...\n",inet_ntoa(dest.sin_addr));
send(connfd,sendBuff,strlen(sendBuff),0); //at first my server sends a hi
sleep(3);
n=recv(connfd,sendBuff,1024,0); //if hi received by the client,then server should receive "Message Received" from the client
sendBuff[n]='\0';
printf("%s",sendBuff);
connfd=accept(listenfd,(struct sockaddr *)&dest,&socksize); }
return 0;
}
clientsocket.c
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int sockfd = 0, n = 0,m=2;
char recvBuff[1024];
struct sockaddr_in serv_addr;
if(argc != 2)
{
printf("\n Usage: %s <ip of server> \n",argv[0]);
return 1;
}
memset(recvBuff, '0',sizeof(recvBuff));
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);
if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return 1;
}
if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
while(m--){ //m is 2 initially,I want that sending and receiving should be done 2 times
n = recv(sockfd,recvBuff,1024,0);
recvBuff[n]='\0'; //"hi" is received
printf("%s",recvBuff);
if(recvBuff=="hi\n")
send(sockfd,"Message Received",strlen("Message Received\n"),0);} //sending "Message received"
return 0;
}
Now sending messages from server to client works fine, but client to server(Message received) is creating problems.Neither it is giving an error, nor correct results,it just gives a blank screen.
You cannot compare strings using the "==" operator.
You need to use strcmp()
So....
if( strcmp( recvBuff, "hi\n" ) == 0 )
send(sockfd,"Message Received",strlen("Message Received\n"),0);
else
printf( "[%s] != [hi\n]\n", recvBuff );
Basically, you have three different issue in your code:
the string comparison (fixed by K Scott Piel).
The print of the received message are not coming out. You need to add '\n' in all your printf functions.
This is the most important issue: after the first communication between the server and the client, you are calling the accept function in the server code. From the man accept page, we can read
The accept() function shall extract the first connection on the
queue of pending connections, create a new socket with the same socket
type protocol and address family as the specified socket, and allocate
a new file descriptor for that socket.
So, after the first communication, your server is waiting for a new connection and your client is waiting for a message from the server. The second communication will never happen.
To solve this issue, you can use fork() API.
Here is a fix proposal using the fork():
clientsocket.c
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int sockfd = 0, n = 0,m=2;
char recvBuff[1024];
struct sockaddr_in serv_addr;
if(argc != 2)
{
printf("\n Usage: %s <ip of server> \n",argv[0]);
return 1;
}
memset(recvBuff, '0',sizeof(recvBuff));
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);
if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return 1;
}
if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
//m is 2 initially,I want that sending and receiving should be done 2 times
while(m--)
{
printf("Waiting from the server ...\n");
n = recv(sockfd,recvBuff,1024,0);
recvBuff[n]= '\0'; //"hi" is received
printf("%s\n", recvBuff);
if(!strncmp(recvBuff, "hi\n", strlen("hi\n")))
{
printf("Send ACK\n");
n = send(sockfd,"Message Received",strlen("Message Received\n"),0);
printf("%d Sent ... \n", n);
}
} //sending "Message received"
return 0;
}
serversocket.c
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <error.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
int main(int argc,char *argv[])
{
int listenfd = 0,qlength=10,connfd = 0,t=5;
int n;
struct sockaddr_in serv;
struct sockaddr_in dest;
socklen_t socksize = sizeof(struct sockaddr_in);
char sendBuff[1024]="hi\n";
pid_t pid;
int m = 2;
//time_t ticks;
listenfd = socket(AF_INET,SOCK_STREAM,0); //socket for listening to connection requests
memset(&serv,'0',sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY);
serv.sin_port=htons(5000);
bind(listenfd,(struct sockaddr *)&serv,sizeof(serv)); //binding the socket to a port
printf("Server started ...\n");
listen(listenfd,2);
connfd=accept(listenfd,(struct sockaddr *)&dest,&socksize); //another socket for sending and receiving on the previously built socket
while(connfd > 0)
{
printf("Incoming connection from %s-sending a hi...\n",inet_ntoa(dest.sin_addr));
pid = fork();
if(pid) {
/* shall continue to listen to new client */
printf("Parent shall continue listening ... \n");
connfd=accept(listenfd,(struct sockaddr *)&dest,&socksize);
} else {
printf("Chlid process: Communication with the client ... \n");
while(m--)
{
printf("try %d - Sending %s ... \n", m, sendBuff);
send(connfd,sendBuff,strlen(sendBuff),0); //at first my server sends a hi
sleep(3);
n=recv(connfd, sendBuff, 1024, 0); //if hi received by the client,then server should receive "Message Received" from the client
sendBuff[n]='\0';
printf("Data received: [%s]\n", sendBuff); /* need to add '\n' so the print will be displayed */
strcpy(sendBuff, "hi\n");
}
printf("Child process will exit\n");
return 0;
}
}
return 0;
}
Related
I want to make a server-client programm.The first thing i can't find is to make the server never shut down and accept each client.I put a while(1) on my server to run but after 3 connections to one client my server stops accepting other connections and i delete this while.I cant find how to build this think.Also i want to create TCP/IP socket so am i making the socket with the right way?
Im working on ubuntu at Visual Studio Code.
Server:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#define PORT 8080
int main(int argc,char* argv[]){
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char *hello = "Hello from server";
while(1){
char buffer[1024] = {0};
printf("Server\n");
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,&opt,
sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,sizeof(address))<0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 1) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
printf("Listening...\n");
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,(socklen_t*)&addrlen))<0) {
perror("accept");
exit(EXIT_FAILURE);
}
valread = read( new_socket , buffer, 1024);
printf("%s\n",buffer );
send(new_socket , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
}
return 0;
}
My client so far:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#define PORT 8080
int main(int argc,char* argv[]){
char* command = (char*) malloc(15*sizeof(char));
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[1024] = {0};
printf("Client\n");
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) {
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
send(sock , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
valread = read( sock , buffer, 1024);
printf("%s\n",buffer );
return 0;
}
You have to put the loop only around the code, which accepts the clients. The server socket itself is only created once.
// Creation of server socket(), bind(), listen()
while (1) {
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
valread = read( new_socket , buffer, 1024);
printf("%s\n",buffer );
send(new_socket , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
}
Furthermore, you should close the client socket at the end of the while block after the communication is finished (i.e. after the printf("Hello message sent\n");:
close(new_socket);
And note, that the clients are served serially this way. They can connect concurrently, but only one client is served at a time. If you need concurrent handling, you can for example fork() several processes, each handling one client, or handle multiple clients in one thread using poll() or select().
I have made one server and one client communicating through UDP sockets. The work that I am trying to do is that client will pass a string in the arguments and that string will be send to the server using UDP sockets. After receiving the string server will again echo(send) the string back to the client.Below are the codes for both:
code for echoClient.c :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define MAXLINE 4096
int main(int argc, char const *argv[])
{
int sockfd;
struct sockaddr_in servAddr;
char sendLine[MAXLINE],recvLine[MAXLINE];
if(argc!=3)
{
printf("echoClient <Ip addr. of the server> <String to be echoed> \n");
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
printf("Error in creating the socket\n");
exit(2);
}
memset(&servAddr,0,sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(6565); // setting up the port
servAddr.sin_addr.s_addr = inet_addr(argv[1]); // using the given ip address of the server
printf("%s\n", argv[2]);
if((sendto(sockfd,(const char *)argv[2],strlen(argv[2]), MSG_CONFIRM,(struct sockaddr *) &servAddr, sizeof(servAddr))!=-1))
{
printf("data is sent to the server\n");
}
else
{
printf("can't send the data to the server\n");
exit(3);
}
int n = recvfrom(sockfd,(char * ) recvLine,MAXLINE,0,(struct sockaddr * )&servAddr,sizeof(servAddr));
if(n==-1)
{
printf("Can't receive the data from the server\n");
exit(4);
}
recvLine[n] = '\0'; // to terminate the received string
printf("%s\n",recvLine);
return 0;
}
code for echoServer.c:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define MAXLINE 4096
int main(int argc, char const *argv[])
{
int sockfd;
struct sockaddr_in servAddr,clientAddr;
char sendLine[MAXLINE],recvLine[MAXLINE];
if(argc!=1)
{
printf("echoServer\n");
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
printf("Error in creating the socket\n");
exit(2);
}
memset(&servAddr,0,sizeof(servAddr));
memset(&clientAddr,0,sizeof(clientAddr));
// filling the details of the server ip and port
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(6565);
servAddr.sin_addr.s_addr = INADDR_ANY; // using the given ip address of the server
if(bind(sockfd,(struct sockaddr * )&servAddr,sizeof(servAddr))<0)
{
printf("Binding of the socket failed\n");
exit(1);
}
printf("Server is Up... Waiting for the client...\n");
int len;
int n = recvfrom(sockfd,(char *) recvLine,MAXLINE,MSG_WAITALL,(struct sockaddr * )&clientAddr,&len);
if(n==-1)
{
printf("can't get the message from the client\n");
exit(2);
}
recvLine[n] = '\0';
printf("Message received from the client is %s\n",recvLine);
if(sendto(sockfd,(char *) recvLine,n,MSG_CONFIRM,(struct sockaddr *)&clientAddr,len)<0)
{
printf("can't send the message to the client\n");
exit(3);
}
return 0;
}
Now the actual problen is that when I am executing the above codes client is able to send the string to the server but server is unable to send the string back to the client.Server gives the error can't send the message to the client.
I am not able to figure out the error which is stopping the server to send the message to the client.Please help me with this.
I am running the echoClient.c with the command :
./a.out 127.0.0.1 hellofromclientside
In the server, you overlooked that the argument len to recvfrom() is a value-result argument, which before the call you have to initialize to the size of the clientAddr in order to get this address, so change
int len;
to
int len = sizeof clientAddr;
Similarly in the client, change
int n = recvfrom(sockfd,(char * ) recvLine,MAXLINE,0,(struct sockaddr * )&servAddr,sizeof(servAddr));
to
int len = sizeof servAddr;
int n = recvfrom(sockfd, recvLine, MAXLINE, 0, (struct sockaddr *)&servAddr, &len);
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 have a simple server and a client. I run the server at some port in my machine and when I try to connect my client to the server, it says network is unreachable. Can someone please suggest me why is it not being able to connect to the server. Please have a look at the files below:
server.c
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[]){
int sockfd, newsockfd, portno;
struct sockaddr_in serv_addr;
char sendmessage[50];
if(argc != 2){
fprintf(stderr, "ERROR, Port number not provided or Command line argument is not 2\n");
exit(1);
}
//creating a socket for the server
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0){
error("ERROR opening socket");
}
portno = atoi(argv[1]);
//describing the attributes for socket address
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if(bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0){
error("Error on binding the socket");
exit(1);
}
//allowing only 1 client to connect to the server at a time
if(listen(sockfd, 1) < 0){
error("Error in listening to the socket");
}
printf("Server is running...... \nWaiting for the connection from the client on port: %d\n", portno);
while(1){
//accepts the connection from the client
newsockfd = accept(sockfd, (struct sockaddr*)NULL, NULL);
if(newsockfd < 0){
error("Error on accepting");
}
strcpy(sendmessage, "Welcome to The Server");
write(newsockfd, sendmessage, strlen(sendmessage));
}
return 0;
}
client.c
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char* argv[]){
int sockfd;
char recvmessage[100];
char sendmessage[100];
int portno;
struct hostent *server;
struct sockaddr_in serv_addr;
if(argc != 3){
fprintf(stderr, "Error, either IP address or port number not provided.\n");
exit(1);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(socket < 0){
error("Error with creating a socket");
}
//check whether the host exist or not
server = gethostbyname(argv[1]);
if(server == NULL){
fprintf(stderr, "ERROR, the host is not defined\n");
exit(0);
}
//creating the socket
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
//connecting the client to the socket
if(connect(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0){
error("Could not connect to the server......");
exit(1);
}
printf("Connection Successful to the Server\n");
return 0;
}
First of all make sure you pass the same port number to both server & client. If the port number is different, communication between server and client won't happen.
Here is the code for local machine. You can change the code a little and pass IP addresses.
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 2348
#define bufferLength 500
int main(int argc, char *argv[])
{
char buffer[bufferLength];
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;
int cpid;
while(1)
{
consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
perror("consocket\n");
if( (cpid = fork()) == 0 )
{
printf("inside child process\n\n\n");
close(mysocket);
close(consocket);
int recivedBytes = recv(consocket, buffer, bufferLength, 0);
buffer[recivedBytes] = '\0';
printf("recieved data %s \n", buffer);
return 0;
}
else
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 2348
int main(int argc, char *argv[])
{
char buffer[] = "My name is khan"; /* +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("127.0.0.1"); /* set destination IP number */
dest.sin_port = htons(PORTNUM); /* set destination port number */
connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr));
len = send(mysocket, buffer, strlen(buffer), 0);
perror("len\n");
/* We have to null terminate the received data ourselves */
buffer[len] = '\0';
printf("sent %s (%d bytes).\n", buffer, len);
close(mysocket);
return EXIT_SUCCESS;
}
Hope this helps
This code is generating "Connection Failed error", (the error generating portion is commented below in the code) even when i am supplying the correct input format eg.
./Client ip text portno
./Client 127.0.0.1 "tushar" 7100
//AUTHOR: TUSHAR MAROO
//Client.c
//header files used
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>
//constants
#define RCVBUFFERSIZE 32
//functions used
void DieWithError(char *errorMessage);
//main program
int main(int argc, char *argv[]){
int sock;
struct sockaddr_in serverAddr;
unsigned short serverPort;
char *serverIp;
char *message;
unsigned int messageLength;
char buffer[RCVBUFFERSIZE];
//condition check deplyed for nuber of arguements not for data in arguements
if((argc<3) || (argc>4)){
fprintf(stderr,"Format: %s <Server's IP> <Your Message> <Port Number>\n",argv[0]);
exit(1);
}
serverIp = argv[1];
message = argv[2];
if(argc == 4){
serverPort = atoi(argv[3]);
} else {
serverPort = 7;
}
//create a socket and check success and handle error
if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0 )
fprintf(stderr, "Socket Creation Fail");
//server details
//bzero((struct sockaddr_in *)(&serverAddr),sizeof(serverAddr));
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr(serverIp);
serverAddr.sin_port = htons(serverPort);
printf("tusharmaroo");
//not working why??
//if (connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0)
//DieWithError("Connection Error..");
//fprintf(stderr,"Connection error");
//this snippet also not working
if (connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0)
DieWithError("connect() failed");
printf("connected....");
messageLength = strlen(message);
if(send(sock, message, messageLength, 0) > 0)
printf("message sent....");
close(sock);
exit(0);
}
//AUTHOR TUSHAR MAROO
//SERVER CODE
//header files
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
//constants declared
#define ALLOWEDCONNECTIONS 5
//external functions
void DieWithError(char *error);
void ClientHandle(int sock);
//main code
int main(int argc, char argv[]){
int serverSock;
int clientSock;
struct sockaddr_in serverAddr;
struct sockaddr_in clientAddr;
unsigned int serverPort;
unsigned int clientLength;
if(argc != 2){
fprintf(stderr,"Format: %d <Port No.>", argv[0]);
//DieWithError("Pass Correct Number of Arguements...");
exit(1);
}
if((serverSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
DieWithError("Socket not Created");
exit(1);
}
serverPort = htons((argv[1]));
//assign address to the server
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(serverPort);
//socket has been created now bind it to some ip and port
if((bind(serverSock,(struct sockaddr *)&serverAddr,sizeof(serverAddr))) < 0){
DieWithError("Binding Failed");
}
if(listen(serverSock,5) < 0){
DieWithError("Listen Failed");
}
for(;;){
clientLength = sizeof(clientAddr);
if((clientSock = accept(serverSock, (struct sockaddr *) &clientAddr, &clientLength)) < 0){
DieWithError("Accept() failed");
exit(1);
}
printf("Handling Client %s ",inet_ntoa(clientAddr.sin_addr));
}
return 0;
}
This is wrong in the server code
serverPort = htons((argv[1]));
This should be
serverPort = htons(atoi(argv[1]));
Are you sure there are no firewall rules causing troubles for you? Ensure that.
If the connect fails you should be able to print out the error using perror or strerror:
perror("Could not connect:");
works for me
client and server are ubuntu 12.04
for server, run in a shell
nc -l 9999
This is on a host with the address "192.168.56.13"
for client, compile code above with "DieWithError" fixed up
void DieWithError(char *errorMessage) { printf("%s",errorMessage); exit(1); }
cc -o foo foo.c
./foo 192.168.56.13 "hello" 9999</strike>
replace the DieWithError() with perror() Then I would guess that it will print out "connection refused" as you seem to have a networking problem with getting the server running on the correct address.
However, if the address in your client is correct the nc program WILL print "hello"
you just altered your program the previous version worked for me. The current version, I don't know if it does.
Like everyone else is saying, use perror() to get proper diagnostics