C socket bind slows down when i switch source ip addresses - sockets

I have a C script that connects to a remote server with a socket and writes a command.
I have to do this as fast as possible and i need to switch from source ip addressess. The problem is, when i switch from ip addresses, the bind slows down for seconds.
I can not find a solution.
the code:
#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()
{
struct sockaddr_in source, destination = {}; //two sockets declared as previously
int sock = 0;
int n = 0;
int datalen = 0;
int pkt = 0;
char* ips[3] = {"10.0.0.1", "10.0.0.2", "10.0.0.3"};
uint8_t *send_buffer;
char recv_buffer[11];
struct sockaddr_storage fromAddr; // same as the previous entity struct sockaddr_storage serverStorage;
unsigned int addrlen; //in the previous example socklen_t addr_size;
struct timeval tv;
tv.tv_sec = 3; /* 3 Seconds Time-out */
tv.tv_usec = 0;
/*Inititalize source to zero*/
memset(&source, 0, sizeof(source)); //source is an instance of sockaddr_in. Initialization to zero
/*Inititalize destinaton to zero*/
memset(&destination, 0, sizeof(destination));
/* setting the destination, i.e our OWN IP ADDRESS AND PORT */
destination.sin_family = AF_INET;
// destination.sin_addr.s_addr = inet_addr("123.456.789.123");
destination.sin_port = htons(43);
/*---- Configure settings of the source address struct, WHERE THE PACKET IS COMING FROM ----*/
/* Address family = Internet */
source.sin_family = AF_INET;
/* Set IP address to localhost */
// source.sin_addr.s_addr = INADDR_ANY;
/* Set port number, using htons function to use proper byte order */
source.sin_port = htons(43);
/* Set all bits of the padding field to 0 */
memset(source.sin_zero, '\0', sizeof source.sin_zero); //optional
int i;
for (i=0; i<60; i++) {
/* creating the socket */
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("Failed to create socket\n");
/*set the socket options*/
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));
if(inet_pton(AF_INET, ips[i%3], &source.sin_addr)<=0) //this is where is switch the ip addresses
{
printf("\n inet_pton error occured\n");
return 1;
}
/*bind socket to the source WHERE THE PACKET IS COMING FROM*/
if (bind(sock, (struct sockaddr *) &source, sizeof(source)) < 0)
printf("Failed to bind socket");
if(inet_pton(AF_INET, "94.198.154.139", &destination.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return 1;
}
if(connect(sock, (struct sockaddr *)&destination, sizeof(destination)) < 0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
printf("check\n");
n = write(sock,"is liveresults.nl\r\n",21);
if (n < 0) error("ERROR writing to socket");
while ( (n = read(sock, recv_buffer, sizeof(recv_buffer)-1)) > 0)
{
recv_buffer[n] = 0;
if(fputs(recv_buffer, stdout) == EOF)
{
printf("\n Error : Fputs error\n");
}
}
if(n < 0)
{
printf("\n Read error \n");
}
close(sock);
}
return 0;
}
edit: i must notice that it slows down afther the first loops for every ip. Because i have 3 ip addresses. After the first round, it slow down for seconds per bind.

I have to bind the local port to 0 instead of the same port as the outgoing port.

Related

I am not able to send data to all clients from a single server

I am using a for loop on the server-side to send data to all clients received from a single client. But it is unable to send to all clients. Instead, it just sends data to the only client who has sent the data. And also it is not printing the here printf line on the server console.
for(int j=0;j<i;j++){
printf("here");
send(fds[j], buffer, strlen(buffer), 0);
}
My server-side code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 9999
int main(int argc, char* argv[]){
int sockfd, ret;
struct sockaddr_in serverAddr;
int newSocket;
struct sockaddr_in newAddr;
char lastchar = 'a';
socklen_t addr_size;
char buffer[1024];
pid_t childpid;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0){
printf("[-]Error in connection.\n");
exit(1);
}
printf("[+]Server Socket is created.\n");
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if(ret < 0){
printf("[-]Error in binding.\n");
exit(1);
}
printf("[+]Bind to port %d\n", 4444);
if(listen(sockfd, 10) == 0){
printf("[+]Listening....\n");
}else{
printf("[-]Error in binding.\n");
}
int fds[10];
int i = 0;
while(1){
newSocket = accept(sockfd, (struct sockaddr*)&newAddr, &addr_size);
fds[i++] = newSocket;
if(newSocket < 0){
exit(1);
}
printf("Connection accepted from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
if((childpid = fork()) == 0){
close(sockfd);
while(1){
recv(newSocket, buffer, 1024, 0);
if(strcmp(buffer, ":exit") == 0){
printf("Disconnected from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
break;
}else{
if(buffer[0]==lastchar){
lastchar = buffer[strlen(buffer)-1];
bzero(buffer, sizeof(buffer));
strcpy(buffer, "Correct!");
}else{
bzero(buffer, sizeof(buffer));
strcpy(buffer, "Wrong!");
}
for(int j=0;j<i;j++){
printf("here");
send(fds[j], buffer, strlen(buffer), 0);
}
bzero(buffer, sizeof(buffer));
}
}
}
}
close(newSocket);
return 0;
}
My Client-side code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 9999
int main(){
int clientSocket, ret;
struct sockaddr_in serverAddr;
char buffer[1024];
clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if(clientSocket < 0){
printf("[-]Error in connection.\n");
exit(1);
}
printf("[+]Client Socket is created.\n");
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if(ret < 0){
printf("[-]Error in connection.\n");
exit(1);
}
printf("[+]Connected to Server.\n");
while(1){
printf("Client: \t");
scanf("%s", &buffer[0]);
send(clientSocket, buffer, strlen(buffer), 0);
if(strcmp(buffer, ":exit") == 0){
close(clientSocket);
printf("[-]Disconnected from server.\n");
exit(1);
}
if(recv(clientSocket, buffer, 1024, 0) < 0){
printf("[-]Error in receiving data.\n");
}else{
printf("Server: \t%s\n", buffer);
}
}
return 0;
}
If I change my server code to the following can anybody tell me how to reply to all clients?
//Example code: A simple server side code, which echos back the received message.
//Handle multiple socket connections with select and fd_set on Linux
#include <stdio.h>
#include <string.h> //strlen
#include <stdlib.h>
#include <errno.h>
#include <unistd.h> //close
#include <arpa/inet.h> //close
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h> //FD_SET, FD_ISSET, FD_ZERO macros
#define TRUE 1
#define FALSE 0
#define PORT 8888
int main(int argc , char *argv[])
{
int opt = TRUE;
int master_socket , addrlen , new_socket , client_socket[30] ,
max_clients = 30 , activity, i , valread , sd;
int max_sd;
struct sockaddr_in address;
char buffer[1025]; //data buffer of 1K
//set of socket descriptors
fd_set readfds;
//a message
char *message = "ECHO Daemon v1.0 \r\n";
//initialise all client_socket[] to 0 so not checked
for (i = 0; i < max_clients; i++)
{
client_socket[i] = 0;
}
//create a master socket
if( (master_socket = socket(AF_INET , SOCK_STREAM , 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
//set master socket to allow multiple connections ,
//this is just a good habit, it will work without this
if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt,
sizeof(opt)) < 0 )
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
//type of socket created
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
//bind the socket to localhost port 8888
if (bind(master_socket, (struct sockaddr *)&address, sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
printf("Listener on port %d \n", PORT);
//try to specify maximum of 3 pending connections for the master socket
if (listen(master_socket, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
//accept the incoming connection
addrlen = sizeof(address);
puts("Waiting for connections ...");
while(TRUE)
{
//clear the socket set
FD_ZERO(&readfds);
//add master socket to set
FD_SET(master_socket, &readfds);
max_sd = master_socket;
//add child sockets to set
for ( i = 0 ; i < max_clients ; i++)
{
//socket descriptor
sd = client_socket[i];
//if valid socket descriptor then add to read list
if(sd > 0)
FD_SET( sd , &readfds);
//highest file descriptor number, need it for the select function
if(sd > max_sd)
max_sd = sd;
}
//wait for an activity on one of the sockets , timeout is NULL ,
//so wait indefinitely
activity = select( max_sd + 1 , &readfds , NULL , NULL , NULL);
if ((activity < 0) && (errno!=EINTR))
{
printf("select error");
}
//If something happened on the master socket ,
//then its an incoming connection
if (FD_ISSET(master_socket, &readfds))
{
if ((new_socket = accept(master_socket,
(struct sockaddr *)&address, (socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
//inform user of socket number - used in send and receive commands
printf("New connection , socket fd is %d , ip is : %s , port : %d
\n" , new_socket , inet_ntoa(address.sin_addr) , ntohs
(address.sin_port));
//send new connection greeting message
if( send(new_socket, message, strlen(message), 0) != strlen(message) )
{
perror("send");
}
puts("Welcome message sent successfully");
//add new socket to array of sockets
for (i = 0; i < max_clients; i++)
{
//if position is empty
if( client_socket[i] == 0 )
{
client_socket[i] = new_socket;
printf("Adding to list of sockets as %d\n" , i);
break;
}
}
}
//else its some IO operation on some other socket
for (i = 0; i < max_clients; i++)
{
sd = client_socket[i];
if (FD_ISSET( sd , &readfds))
{
//Check if it was for closing , and also read the
//incoming message
if ((valread = read( sd , buffer, 1024)) == 0)
{
//Somebody disconnected , get his details and print
getpeername(sd , (struct sockaddr*)&address , \
(socklen_t*)&addrlen);
printf("Host disconnected , ip %s , port %d \n" ,
inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
close( sd );
client_socket[i] = 0;
}
//Echo back the message that came in
else
{
//set the string terminating NULL byte on the end
//of the data read
buffer[valread] = '\0';
send(sd , buffer , strlen(buffer) , 0 );
}
}
}
}
return 0;
}
When you call fork(), the child process effectively receives its own separate copy of the parent process's address-space. Since the child process's address-space is separate and independent from that of its parent process, any subsequent changes to variables in the parent process's address space will not be seen by the child process.
Since your server is calling fork() for each new TCP connection that is received, that means that each new TCP connection is getting its own address-space that includes it and any already-accepted sockets, but will never include any sockets that are accepted on the server after that client's process was spawned. That is likely why you aren't seeing all the file descriptors you expect in your fds array, when you iterate over it calling send().
My advice is to simply get rid of the fork() call. If you want to keep (and iterate over) a list of all connected clients' file-descriptors, then its much simpler to use a single-process model rather than a process-per-client model. If you need to react to incoming input data from any of the clients, you can use non-blocking I/O and block instead inside select() or poll() until one of the file descriptors in your list has incoming data ready for you to read.

Unable to receive TCP data on particular IP

I am trying to implement TCP client, server program in C on Linux system. Here are my codes.
Client Source Code :
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
char *address;
// Create socket
int client_socket;
client_socket = socket(AF_INET, SOCK_STREAM, 0);
// Set - Up Server Address
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(8001);
inet_aton(address, &server_address.sin_addr.s_addr);
// Connect to the server
int connect_stat;
connect_stat = connect(client_socket, (struct sockaddr *) &server_address, sizeof(server_address));
if(connect_stat == -1)
printf("Not Connected\n");
else
printf(" Connected \n");
// Recieve from server
char response[256];
recv(client_socket, &server_address, sizeof(server_address), 0);
// Printing the Response data
printf("Data Recieved : %s\n",response);
// Destroy the socket
close(client_socket);
return 0;
}
Server Source Code :
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
// Address
char *address;
address = argv[1];
// Create message to send
char message[256] = "Connection Established";
// Create server socket
int server_socket;
server_socket = socket(AF_INET, SOCK_STREAM, 0);
// Set - Up Server Address
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(8001);
inet_aton(address, &server_address.sin_addr.s_addr);
// Bind it to an IP and PORT
bind(server_socket, (struct sockaddr *) &server_address, sizeof(server_address));
// Start listenting on address
listen(server_socket, 5);
// Start accepting the clients;
int client_socket;
client_socket = accept(server_socket, NULL, NULL);
// Send some data back to client
send(client_socket, message, sizeof(message), 0);
// Close the socket
close(server_socket);
close(client_socket);
return 0;
}
On passing an IP like 192.168.1.xxx to both client and server, server starts waiting for the clients but client always show not connected and thus no data received.
Client output :
root#kali:/home/mayank/Desktop/tcp_chat# ./tcp_client 192.168.1.111
Not Connected
Data Recieved :
But if i use INADDR_ANY instead of specific IP, it works. I know INADDR_ANY basically means it binds to all IP address, but why it is not binding to specific IP address which i want. Any suggestions, where i am wrong.
Instead of inet_aton(), you can also use
server_address.sin_addr.s_addr = inet_addr("IP address");
And use perror() after every function, like
client_socket = socket(...);
if (client_socket == -1)
perror("socket");
You are not doing any error checking, except on the connect() call. For example, you are getting an ENOTSOCK error because you are not checking whether socket() succeeds or fails.
Beyond that, on the client side, this statement:
inet_aton(address, &server_address.sin_addr.s_addr);
Should be this instead:
inet_aton(address, &server_address.sin_addr);
inet_aton() expects a pointer to a struct in_addr, but you are passing it a pointer to a uint32_t instead. In fact, the original code should not have even compiled because of that.
But, more importantly, your address variable is uninitialized, so you are passing a bad memory pointer to inet_aton(), and not checking its return value for failure.
Even if you could connect to the server, you are also passing the wrong output buffer to recv(), so you would end up writing garbage to the console.
Try this instead:
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("usage: %s <IPv4 address>\n", argv[0]);
return 0;
}
// Set - Up Server Address
struct sockaddr_in server_address = {0};
server_address.sin_family = AF_INET;
server_address.sin_port = htons(8001);
if (inet_aton(argv[1], &server_address.sin_addr) != 0)
{
printf("invalid IPv4 address specified\n");
return 0;
}
// Create socket
int client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (client_socket == -1)
{
perror("socket() failed");
return 0;
}
// Connect to the server
if (connect(client_socket, (struct sockaddr *) &server_address, sizeof(server_address)) == -1)
{
perror("Not Connected");
}
else
{
printf("Connected\n");
// Receive from server
char response[256];
int numRecvd = recv(client_socket, response, sizeof(response), 0);
// Printing the Response data
if (numRecvd == -1)
perror("recv() failed");
else if (numRecvd == 0)
printf("Disconnected by server\n");
else
printf("Data Received: [%d] %.*s\n", numRecvd, numRecvd, response);
}
// Destroy the socket
close(client_socket);
return 0;
}
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
// Set - Up Server Address
struct sockaddr_in server_address = {0};
server_address.sin_family = AF_INET;
server_address.sin_port = htons(8001);
if (argc >= 2)
{
if (inet_aton(argv[1], &server_address.sin_addr) != 0)
{
printf("invalid IPv4 address specified\n");
return 0;
}
}
else
server_address.sin_addr.s_addr = INADDR_ANY;
// Create message to send
char message[256] = "Connection Established";
// Create server socket
int server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server_socket == -1)
{
perror("socket() failed");
return 0;
}
// Bind it to an IP and PORT
if (bind(server_socket, (struct sockaddr *) &server_address, sizeof(server_address)) == -1)
{
perror("bind() failed");
}
// Start listenting on address
else if (listen(server_socket, 5) == -1)
{
perror("listen() failed");
}
// Start accepting the clients
else
{
int client_socket = accept(server_socket, NULL, 0);
if (client_socket == -1)
{
perror("accept() failed");
}
else
{
// Send some data back to client
int numSent = send(client_socket, message, sizeof(message), 0);
if (numSent == -1)
perror("send() failed");
else
printf("Data Sent: [%d] %.*s\n", numSent, numSent, message);
// Close the socket
close(client_socket);
}
}
// Destroy the socket
close(server_socket);
return 0;
}

handling multiple clients using select

As i already asked similar questions but didn't get a solution. Hence i put this problem again with the whole code. Please tell me how can i acheive this goal
1) i have a client which sends to mainserver (127.0.0.1) a message and main server forwards it to server2 (127.0.0.2)
2) Server2 sends a message to the mainserver and mainserver forwards it to client.
Problem 1) : Although i receive the datas from client but they are not sent to server2.
Problem 2) :I dont receive any data from server2
//SERVER
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/select.h>//use select() for multiplexing
#include <sys/fcntl.h> // for non-blocking
#define MAX_LENGTH 100000
#define PORT 1901
/* Select() params
* int select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
* FD_SET(int fd, fd_set *set);
* FD_CLR(int fd, fd_set *set);
* FD_ISSET(int fd, fd_set *set);
* FD_ZERO(fd_set *set);
*/
void error(char *message)
{
perror(message);
exit(1);
}
int main()
{
// select parameters declared
fd_set original_socket;
fd_set original_stdin;
fd_set readfds;
fd_set writefds;
struct timeval tv;
int numfd, numfd2;
// socket parameters declared
int socket_fd_ob, socket_fd_hm;
int bytes_read, bytes_sent;
char address_length, address_length2;
char recieve_data[MAX_LENGTH];
char send_data[MAX_LENGTH];
struct sockaddr_in server_address_ob, server_address_hm, client_address;
int z = 0;
//Socket creation done separately for both OBCU and HM communications
if ((socket_fd_ob = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
error("socket()");
}
if ((socket_fd_hm = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
error("socket()");
}
fcntl(socket_fd_ob, F_SETFL, O_NONBLOCK); //set socket to non-blocking
fcntl(socket_fd_hm, F_SETFL, O_NONBLOCK); //set socket to non-blocking
// clear the set ahead of time
FD_ZERO(&original_socket);
FD_ZERO(&original_stdin);
FD_ZERO(&readfds);
FD_ZERO(&writefds);
// add our descriptors to the set (0 - stands for STDIN)
FD_SET(socket_fd_ob, &original_socket);//instead of 0 put socket_fd_ob
FD_SET(socket_fd_ob, &readfds);
FD_SET(0,&original_stdin);
FD_SET(0, &writefds);
// the n param in select()
numfd = socket_fd_ob + 1;
numfd2 = socket_fd_hm + 1;
// wait until either socket has data ready to be recv()d (timeout 10.5 secs)
tv.tv_sec = 0.7;
tv.tv_usec = 500000;
server_address_ob.sin_family = AF_INET;
server_address_ob.sin_port = htons(1901);
server_address_ob.sin_addr.s_addr = inet_addr("127.0.0.1");
bzero(&(server_address_ob.sin_zero),sizeof(server_address_ob));
server_address_hm.sin_family = AF_INET;
server_address_hm.sin_port = htons(1901);
server_address_hm.sin_addr.s_addr = inet_addr("127.0.0.2");
bzero(&(server_address_ob.sin_zero),sizeof(server_address_hm));
// Bind socket to the particular addresses
if (bind(socket_fd_ob,(struct sockaddr *)&server_address_ob, sizeof(struct sockaddr)) == -1)
{
error("bind()");
}
if (bind(socket_fd_hm,(struct sockaddr *)&server_address_hm, sizeof(struct sockaddr)) == -1)
{
error("bind()");
}
address_length = sizeof(struct sockaddr);
address_length2 = sizeof(struct sockaddr);
printf("\nMain server waiting for client to respond...\n");
fflush(stdout);
while (1)
{
readfds = original_socket;
writefds = original_stdin;//problem
int recieve = select(numfd, &readfds, &writefds,/*NULL,*/ NULL, &tv);
int sent = select(numfd2, &readfds, &writefds,/*NULL,*/ NULL, &tv);
if (recieve == -1 || sent == -1)
{
perror("select"); // error occurred in select()
}
else if (recieve == 0 || sent == 0)
{
printf("Timeout occurred! No data after 1.5 seconds.\n");
}
else
{
// one or both of the descriptors have data
if (FD_ISSET(socket_fd_ob, &readfds)) //if set to read
{
FD_CLR(socket_fd_ob, &readfds);
if (bytes_read = recvfrom(socket_fd_ob,recieve_data,MAX_LENGTH,0,(struct sockaddr *)&server_address_ob, &address_length)>0)
{
for (z = 0; z < bytes_read; ++z) {
FD_ISSET(socket_fd_hm, &writefds);
FD_CLR(socket_fd_hm, &writefds);
//recvfrom speech recognition client and decide what to send to HM accordingly..
send_data[bytes_read] = recieve_data[bytes_read];
//block call, will wait till client enters something, before proceeding
//send the corresponding to HM
bytes_sent = sendto(socket_fd_hm,send_data,strlen(send_data)+1,0,(struct sockaddr *)&server_address_hm, &address_length2);
fflush(stdout);
}
// 02x, #x,X
printf("\n(%s , %d) rcvd: %s\n",inet_ntoa(server_address_ob.sin_addr),ntohs(server_address_ob.sin_port),recieve_data);
printf("\n(%s , %d) sent: %s\n",inet_ntoa(server_address_hm.sin_addr),ntohs(server_address_hm.sin_port),send_data);
recieve_data[bytes_read] = '\0'; //add null to the end of the buffer
send_data[bytes_read] = '\0'; //add null to the end of the buffer
}
else if (bytes_read = recvfrom(socket_fd_hm,recieve_data,MAX_LENGTH,0,(struct sockaddr *)&server_address_hm, &address_length)>0)
{
for (z = 0; z < bytes_read; ++z) {
FD_ISSET(socket_fd_ob, &writefds);
FD_CLR(socket_fd_ob, &writefds);
send_data[bytes_read] = recieve_data[bytes_read];
//block call, will wait till client enters something, before proceeding
//send the corresponding to HM
bytes_sent = sendto(socket_fd_ob,send_data,strlen(send_data)+1,0,(struct sockaddr *)&server_address_ob, &address_length2);
fflush(stdout);
}
// 02x, #x,X
printf("\n(%s , %d) rcvd: %s\n",inet_ntoa(server_address_hm.sin_addr),ntohs(server_address_hm.sin_port),recieve_data);
printf("\n(%s , %d) sent: %s\n",inet_ntoa(server_address_ob.sin_addr),ntohs(server_address_ob.sin_port),send_data);
recieve_data[bytes_read] = '\0'; //add null to the end of the buffer
send_data[bytes_read] = '\0'; //add null to the end of the buffer
}
else
{
printf("error noted");
}
} //end if set to read
} //end else
}//end while
close (socket_fd_ob);
close (socket_fd_hm);
return 0;
}
Please suggest me with code samples. i am new to this topic and didn't have a broad view yet.
Thanks

How to use select() in UDP Sockets to read and write from client to server

I'm trying to make a chat application using sockets, and I want them both to be able to write and read simultaneously. So I did some research and found that I/O multiplexing like select() will fix this problem. But I still have one problem. After I compile it and run it, one of the two programs doesn't receive the message 'till after one responds. So for example, the server sends a message to the client right? Then the client won't see the message until AFTER the client responds. Below you can find an example of this as well as the source code.
Client: hi
Server: hello
Client said "hi"
And the same for client etc
//SERVER
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/select.h>//use select() for multiplexing
#include <sys/fcntl.h> // for non-blocking
#define MAX_LENGTH 1024
/* Select() params
* int select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
* FD_SET(int fd, fd_set *set);
* FD_CLR(int fd, fd_set *set);
* FD_ISSET(int fd, fd_set *set);
* FD_ZERO(fd_set *set);
*/
void error(char *message)
{
perror(message);
exit(1);
}
int main()
{
fd_set original_socket;
fd_set original_stdin;
fd_set readfds;
fd_set writefds;
struct timeval tv;
int numfd;
int socket_fd, bytes_read;
unsigned int address_length;
char recieve_data[MAX_LENGTH],send_data[MAX_LENGTH];
struct sockaddr_in server_address , client_address;
if ((socket_fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
error("socket()");
}
int flags = fcntl(socket_fd, F_GETFL);
flags |= O_NONBLOCK;
fcntl(socket_fd, F_SETFL, flags);
//fcntl(socket_fd, F_SETFL, O_NONBLOCK); //set socket to non-blocking
// clear the set ahead of time
FD_ZERO(&original_socket);
FD_ZERO(&original_stdin);
FD_ZERO(&readfds);
FD_ZERO(&writefds);
// add our descriptors to the set (0 - stands for STDIN)
FD_SET(socket_fd, &original_socket);//instead of 0 put socket_fd
FD_SET(socket_fd, &readfds);
FD_SET(0,&original_stdin);
FD_SET(0, &writefds);
// since we got s2 second, it's the "greater", so we use that for
// the n param in select()
numfd = socket_fd + 1;
// wait until either socket has data ready to be recv()d (timeout 10.5 secs)
tv.tv_sec = 10;
tv.tv_usec = 500000;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(5000);
server_address.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_address.sin_zero),8);
if (bind(socket_fd,(struct sockaddr *)&server_address, sizeof(struct sockaddr)) == -1)
{
error("bind()");
}
address_length = sizeof(struct sockaddr);
printf("\nUDP_Server Waiting for client to respond...\n");
fflush(stdout);
printf("Type (q or Q) at anytime to quit\n");
while (1)
{
readfds = original_socket;
writefds = original_stdin;//problem
int recieve = select(numfd, &readfds, &writefds,/*NULL,*/ NULL, &tv);
if (recieve == -1)
{
perror("select"); // error occurred in select()
}
else if (recieve == 0)
{
printf("Timeout occurred! No data after 10.5 seconds.\n");
}
else
{
// one or both of the descriptors have data
if (FD_ISSET(socket_fd, &readfds)) //if set to read
{
FD_CLR(socket_fd, &readfds);
bytes_read = recvfrom(socket_fd,recieve_data,MAX_LENGTH,0,(struct sockaddr *)&client_address, &address_length); //block call, will wait till client enters something, before proceeding
recieve_data[bytes_read] = '\0'; //add null to the end of the buffer
if((strcmp(recieve_data , "q") == 0) || (strcmp(recieve_data , "Q") == 0)) { //if client quit, then quit also
printf("\nClient has exited the chat.\n");
break;
}
printf("\n(%s , %d) said: %s\n",inet_ntoa(client_address.sin_addr),ntohs(client_address.sin_port),recieve_data);
}
else if (FD_ISSET(/*socket_fd*/0, &writefds)) //if set to write
//else
{
FD_CLR(0, &writefds);
printf("SERVER: ");
fgets (send_data, MAX_LENGTH, stdin); //input the name with a size limit of MAX_LENGTH
if ((strlen(send_data)>0) && (send_data[strlen (send_data) - 1] == '\n')) //if there is a trailing \n, remove it
{
send_data[strlen (send_data) - 1] = '\0';
}
if ((strcmp(send_data , "q") == 0) || (strcmp(send_data , "Q") == 0)) { //if user enters q, then quit
sendto(socket_fd,send_data,strlen(send_data),0,(struct sockaddr *)&client_address, sizeof(struct sockaddr));
break;
}
sendto(socket_fd,send_data,strlen(send_data),0,(struct sockaddr *)&client_address, sizeof(struct sockaddr));
fflush(stdout);
}
else printf("\nOOPS! What happened? SERVER");
} //end else
}//end while
close (socket_fd);
return 0;
}
At first I thought it was a trailing newline, but I took care of that possibility already by changing the '/n' to '/0' if it exists. I really don't understand why this is happening!
//CLIENT
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h> //host struct
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/select.h>//use select() for multiplexing
#include <sys/fcntl.h> // for non-blocking
#define MAX_LENGTH 1024
#define HOST "localhost" //127.0.0.1
void error(char *message)
{
perror(message);
exit(1);
}
int main()
{
fd_set original_socket;
fd_set original_stdin;
fd_set readfds;
fd_set writefds;
struct timeval tv;
int numfd;
int socket_fd,bytes_recieved;
unsigned int address_length;
struct sockaddr_in server_address;
struct hostent *host;
char send_data[MAX_LENGTH],recieve_data[MAX_LENGTH];
host = (struct hostent *) gethostbyname((char *)HOST);//127.0.0.1
if ((socket_fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
error("socket()");
}
int flags = fcntl(socket_fd, F_GETFL);
flags |= O_NONBLOCK;
fcntl(socket_fd, F_SETFL, flags);
//fcntl(socket_fd, F_SETFL, O_NONBLOCK); //set socket to non-blocking
// clear the set ahead of time
FD_ZERO(&original_socket);
FD_ZERO(&original_stdin);
FD_ZERO(&readfds);
FD_ZERO(&writefds);
// add our descriptors to the set (0 - stands for STDIN)
FD_SET(socket_fd, &original_socket);//instead of 0 put socket_fd
FD_SET(socket_fd, &readfds);
FD_SET(0,&original_stdin);
FD_SET(0, &writefds);
// since we got s2 second, it's the "greater", so we use that for
// the n param in select()
numfd = socket_fd + 1;
// wait until either socket has data ready to be recv()d (timeout 10.5 secs)
tv.tv_sec = 10;
tv.tv_usec = 500000;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(5000);
server_address.sin_addr = *((struct in_addr *)host->h_addr);
bzero(&(server_address.sin_zero),8);
address_length = sizeof(struct sockaddr);
printf("Type (q or Q) at anytime to quit\n");
while (1)
{
readfds = original_socket;
writefds = original_stdin;//problem
int recieve = select(numfd, &readfds, /*NULL*/&writefds, NULL, &tv);
if (recieve == -1)
{
perror("select"); // error occurred in select()
}
else if (recieve == 0)
{
printf("Timeout occurred! No data after 10.5 seconds.\n");
}
else
{
// one or both of the descriptors have data
if (FD_ISSET(socket_fd, &readfds)) //if set to read
{
FD_CLR(socket_fd, &readfds);//clear the set
bytes_recieved = recvfrom(socket_fd,recieve_data, sizeof(recieve_data),0,(struct sockaddr *)&server_address,&address_length);
recieve_data[bytes_recieved]= '\0';
if((strcmp(recieve_data , "q") == 0) || (strcmp(recieve_data , "Q") == 0)) //if client quit, then quit also
{
printf("\nServer has exited the chat.\n");
break;
}
printf("\n(%s , %d) said: %s\n",inet_ntoa(server_address.sin_addr),ntohs(server_address.sin_port),recieve_data);
//inet_ntoa returns an ip address ipv4 style, ex: 127.0.0.1, and ntohs returns the port in the converted byte ordering
}
else if (FD_ISSET(0/*socket_fd*/, &writefds)) //if set to write
//else
{
FD_CLR(0, &writefds);
printf("ClIENT: ");
fgets (send_data, MAX_LENGTH, stdin);
if ((strlen(send_data)>0) && (send_data[strlen (send_data) - 1] == '\n')) //remove trailing newline, if exists
{
send_data[strlen (send_data) - 1] = '\0';
}
if ((strcmp(send_data , "q") == 0) || strcmp(send_data , "Q") == 0) //if user quits, then send an invisible message to server to quit also
{
sendto(socket_fd, send_data, strlen(send_data), 0, (struct sockaddr *)&server_address, sizeof(struct sockaddr));
break;
}
else
{
sendto(socket_fd, send_data, strlen(send_data), 0, (struct sockaddr *)&server_address, sizeof(struct sockaddr));
}
}
else printf("\nOOPS! What happened? CLIENT");
} //end else
} // end while
close (socket_fd);
}
Your mistake is that with select() you wait for the socket to be readable (which is right) and STDIN to be writable (which is wrong, since the terminal is writable most of the time). You have to wait for both socket or STDIN to be readable, i. e. both file descriptors are to be set in readfds, and NULL can be passed instead of &writefds.

Socket programming connect error

I received the error: `connect failed: connection refused` from the following code. Server side code runs fine, but when I run the client side I get the connect failed error. I am using Ubuntu.
server side run: `./server.out 1234`
client side run: `.client.out 127.0.0.1 input.txt 1234`
Client code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
//#include "Practical.h"
// check error
void DieWithError(char *errorMessage)
{
perror(errorMessage);
exit(1);
}
void DieWithUserMessage(const char *msg, const char *detail) {
fputs(msg, stderr);
fputs(": ", stderr);
fputs(detail, stderr);
fputc('\n', stderr);
exit(1);
}
void DieWithSystemMessage(const char *msg) {
perror(msg);
exit(1);
}
//define buffer size
enum sizeConstants {
MAXSTRINGLENGTH = 128,
BUFSIZE = 512,
};
int main(int argc, char *argv[]) {
char buffer[BUFSIZE];
//FILE *fp,*fpOut; // declare file pointer
if (argc < 3 || argc > 4) // Test for correct number of arguments
DieWithUserMessage("Parameter(s)","<Server Address> <Echo Word> [<Server Port>]");
char *servIP = argv[1]; // First arg: server IP address (dotted quad)
char *echoString = argv[2]; // Second arg: string to echo
// Third arg (optional): server port (numeric). 7 is well-known echo port
in_port_t servPort = (argc == 4) ? atoi(argv[3]) : 7;
// Create a reliable, stream socket using TCP
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0)
DieWithSystemMessage("socket() failed");
// Construct the server address structure
struct sockaddr_in servAddr; // Server address
memset(&servAddr, 0, sizeof(servAddr)); // Zero out structure
servAddr.sin_family = AF_INET; // IPv4 address family
// Convert address
int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr);
if (rtnVal == 0)
DieWithUserMessage("inet_pton() failed", "invalid address string");
else if (rtnVal < 0)
DieWithSystemMessage("inet_pton() failed");
servAddr.sin_port = htons(servPort); // Server port
// Establish the connection to the echo server
if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
DieWithSystemMessage("connect() failed");
/*
//start reading file input from computer
char buf[1000];
fp =fopen("input.txt","r");//open the file
if (!fp){
printf("it failed!\n");
return 1;
}
while(fgets (buf, 1000, fp)!=NULL) { // take the file input value in buf char array
//printf("The input value in program.txt file: %s",buf);
printf("Received Message from server: ");
*/
size_t echoStringLen = strlen(echoString); // Determine input length
// Send the string to the server
ssize_t numBytes = send(sock, echoString, echoStringLen, 0);
if (numBytes < 0)
DieWithSystemMessage("send() failed");
else if (numBytes != echoStringLen)
DieWithUserMessage("send()", "sent unexpected number of bytes");
// Receive the same string back from the server
unsigned int totalBytesRcvd = 0; // Count of total bytes received
// Setup to print the echoed string
while (totalBytesRcvd < echoStringLen) {
// I/O buffer
/* Receive up to the buffer size (minus 1 to leave space for
a null terminator) bytes from the sender */
numBytes = recv(sock, buffer, BUFSIZE - 1, 0);
if (numBytes < 0)
DieWithSystemMessage("recv() failed");
else if (numBytes == 0)
DieWithUserMessage("recv()", "connection closed prematurely");
totalBytesRcvd += numBytes; // Keep tally of total bytes
buffer[numBytes] = '\0'; // Terminate the string!
printf("%s",buffer);
//fputs(buffer, stdout); // Print the echo buffer
}
//fpOut = fopen("gcd.txt","w"); // open the gcd txt file in write mode
//fprintf(fpOut,"%s",buffer );// write the gcd value in gcd text file
//fputc('\n', stdout);
//fclose(fpOut);
//fclose(fp);
return 0;
close(sock);
exit(0);
}
Server code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
//#include "Practical.h"
void DieWithError(char *errorMessage)
{
perror(errorMessage);
exit(1);
}
void DieWithUserMessage(const char *msg, const char *detail) {
fputs(msg, stderr);
fputs(": ", stderr);
fputs(detail, stderr);
fputc('\n', stderr);
exit(1);
}
void DieWithSystemMessage(const char *msg) {
perror(msg);
exit(1);
}
static const int MAXPENDING = 5; // Maximum outstanding connection requests
int main(int argc, char *argv[]) {
if (argc != 2) // Test for correct number of arguments
DieWithUserMessage("Parameter(s)", "<Server Port>");
in_port_t servPort = atoi(argv[1]); // First arg: local port
// Create socket for incoming connections
int servSock; // Socket descriptor for server
if ((servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithSystemMessage("socket() failed");
// Construct local address structure
struct sockaddr_in servAddr; // Local address
memset(&servAddr, 0, sizeof(servAddr)); // Zero out structure
servAddr.sin_family = AF_INET; // IPv4 address family
servAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Any incoming interface
servAddr.sin_port = htons(servPort); // Local port
// Bind to the local address
if (bind(servSock, (struct sockaddr*) &servAddr, sizeof(servAddr)) < 0)
DieWithSystemMessage("bind() failed");
// Mark the socket so it will listen for incoming connections
if (listen(servSock, MAXPENDING) < 0)
DieWithSystemMessage("listen() failed");
for (;;) { // Run forever
struct sockaddr_in clntAddr; // Client address
// Set length of client address structure (in-out parameter)
socklen_t clntAddrLen = sizeof(clntAddr);
printf("\nIam here\n");
// Wait for a client to connect
int clntSock = accept(servSock, (struct sockaddr *) &clntAddr, &clntAddrLen);
if (clntSock < 0)
DieWithSystemMessage("accept() failed");
// clntSock is connected to a client!
char clntName[INET_ADDRSTRLEN]; // String to contain client address
if (inet_ntop(AF_INET, &clntAddr.sin_addr.s_addr, clntName,sizeof(clntName)) != NULL)
printf("Got response from client: %s/%d\n", clntName, ntohs(clntAddr.sin_port));
else
puts("Unable to get client address");
HandleTCPClient(clntSock);
}
// NOT REACHED
}
HandleTCPClient:`#define RCVBUFSIZE 1024 /* Size of receive buffer */
void DieWithError(char errorMessage); / Error handling function */
void HandleTCPClient(int clntSocket) {
FILE *fp;
char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */
int recvMsgSize; /* Size of received message */
/* Receive message from client */
if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
DieWithError("recv() failed");
printf("Server asked file name from Client side:: %s", echoBuffer);
fp =fopen("echoBuffer","r");//open the file
if (!fp){
printf("it failed!\n");
//return 1;
}
//int i,j;
//sscanf(echoBuffer, "%d %d", &i,&j);// take the two number from client and convert string to integer.
//sprintf(echoBuffer,"%d",gcd(i,j)); // call the gcd method.
/* Send received string and receive again until end of transmission */
while (recvMsgSize > 0){ /* zero indicates end of transmission */
/* Echo message back to client */
if (send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize)
DieWithError("send() failed");
/* See if there is more data to receive */
if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
DieWithError("recv() failed");
}
fclose(fp);
close(clntSocket); /* Close client socket */
}
HandleTCPclient received command from client like input.txt and check that file and send back to the client but i got segmentation fault(core dumped). here input.txt contain just one text file
enter code here
Your code is not using your supplied port, but it trying to connect to 7, you may not have a echo server running. Try changing to
in_port_t servPort = (argc ==4) ? atoi(argv[3]) : 7;