Unable to receive TCP data on particular IP - sockets

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;
}

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.

Bluetooth communication of android device with raspberrypi -getting error as connection refused

I have tried socket programming for Bluetooth communication with raspberrypi. But every time I am getting connection refused as error .I have installed all necessary Bluetooth packages on pi.
client code
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main(int argc, char **argv)
{
struct sockaddr_rc addr = { 0 };
int s, status;
char dest[18] = "01:23:45:67:89:AB";
// allocate a socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
// set the connection parameters (who to connect to)
addr.rc_family = AF_BLUETOOTH;
addr.rc_channel = (uint8_t) 1;
str2ba( dest, &addr.rc_bdaddr );
// connect to server
status = connect(s, (struct sockaddr *)&addr, sizeof(addr));
// send a message
if( status == 0 ) {
status = write(s, "hello!", 6);
}
if( status < 0 ) perror("uh oh");
close(s);
return 0;
}
Server code:
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main(int argc, char **argv)
{
struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
char buf[1024] = { 0 };
int s, client, bytes_read;
socklen_t opt = sizeof(rem_addr);
// allocate socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
// bind socket to port 1 of the first available
// local bluetooth adapter
loc_addr.rc_family = AF_BLUETOOTH;
loc_addr.rc_bdaddr = *BDADDR_ANY;
loc_addr.rc_channel = (uint8_t) 1;
bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
// put socket into listening mode
listen(s, 1);
// accept one connection
client = accept(s, (struct sockaddr *)&rem_addr, &opt);
ba2str( &rem_addr.rc_bdaddr, buf );
fprintf(stderr, "accepted connection from %s\n", buf);
memset(buf, 0, sizeof(buf));
// read data from the client
bytes_read = read(client, buf, sizeof(buf));
if( bytes_read > 0 ) {
printf("received [%s]\n", buf);
}
// close connection
close(client);
close(s);
return 0;
}
when visibility of my device is off then it says "host is down"
And when visibility is on and when I pair device it says connection is refused.

Only the first message is reaching from client to server in socket programming but the further messages sent from client are not reaching the server

I have put a while loop in both client and server to send and recieve messages but only first message is reaching the server. There after the messages sent from client are not reaching the server.
server side:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
int main(int argc, char *argv[])
{
int socks,portno;
struct sockaddr_in server,client;
int newsock,n;
char buffer[5000];
int cli_len;
if(argc < 2)
{
perror("\ninsufficient inputs");
exit(1);
}
if((socks = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
perror("\nsocket creation error");
exit(1);
}
printf("\nsocket successfully created");
bzero((char *) &server, sizeof(server));
server.sin_family = AF_INET;
portno = atoi(argv[1]);
server.sin_port = htons(portno);
server.sin_addr.s_addr = INADDR_ANY;
if((bind(socks,(struct sockaddr *) &server,sizeof(server))) > 0)
{ //socket binding
perror("\nsocket binding failed");
exit(1);
}
printf("\nsocket binding successfull");
if(listen(socks,5) < 0)
{
perror("\nerror in listening");
exit(1);
}
printf("\nlisten succesfull");
while(1)
{
cli_len = sizeof client;
newsock = accept(socks, (struct sockaddr *) &client,&cli_len);
bzero(buffer,5000);
if( (n = recv(newsock,buffer,5000,0)) < 0) //recieving the message
{
perror("\nreading from socket failed");
exit(1);
}
printf("read message:%s",buffer);
//bzero(buffer,5000);
//buffer[5000] = "got ur message";
if(( n = write(newsock,"got ur message",14)) < 0)
{
perror("\nwrite failed");
exit(1);
}
}
return 0;
}
Client:
on the client side it's asking the next message to be sent but all the messages after first message are not reaching the server.
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
int main(int argc, char *argv[])
{
struct sockaddr_in server;
struct hostent *host;
char buffer[5000];
int portno,socky,n;
if(argc < 3)
{
perror("insufficient inputs"); //checking the inputs
exit(1);
}
if((socky = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
perror("\nerror in socket creation"); //socket creation
exit(1);
}
printf("\nsocket successfully created");
server.sin_family = AF_INET;
portno = atoi(argv[2]);
server.sin_port = htons(portno);
host = gethostbyname(argv[1]);
if(host == NULL)
{
perror("\nerror in getting host address");
exit(1);
}
memcpy (&server.sin_addr.s_addr, host->h_addr,host->h_length);
if((connect(socky,&server,sizeof(server)))<0) //connecting to server
{
perror("\nerror in connection");
exit(1);
}
while(1)
{
bzero(buffer,5000);
printf("\nenter the message");
fgets(buffer,5000,stdin);
printf("u have entered the messge:%s",buffer);
if((n = write(socky,buffer,strlen(buffer))) < 0) //writing to socket
{
perror("\nerror in writing the message");
exit(1);
}
bzero(buffer,1000);
if (n = (read(socky,buffer,1000)) < 0) //reading from socket
{
perror("\nerror in reading from socket");
exit(1);
}
printf("\nmessage recieved:%s",buffer);
}
return 0;
}

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;

Fail to connect two sockets which are bound with two public IP address in a server

I tried to setup a XSTUNT server on Linux(http://www.cis.nctu.edu.tw/~gis87577/xDreaming/XSTUNT/index.html) to do p2p traversal, but failed. I read the source code of it. I found the application creates two TCP sockets and then bind them to the two public IP addresses respectively. The remote client is able to connect only one of the public IP address.
So I wrote a simple server application to test this environment.
On the remote client, I use this two commands
"nc [public IP_A] [PORT]" and
"nc [public IP_B] [PORT]"
to try to connect to the server. Only one is successful, while the other fail. I have sniffer the traffic on the client, the nc which is failed can not get "SYN-ACK" package from the server. Is it the route problem? My two public interfaces do NOT have special gateway. Because I use PPPoE to connect to the Internet. So I just get ppp0 and ppp1. I don't know how to change the route table if the route table cause this problem.
However, If I do these two command on the server which is running my sever application, both commands are successful. Who can tell me why?
NOTE: I compiled this server application on Windows with cygwin. The result is the same.
Here is the code of my server application
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SERVPORT 3333 /* Listen Port */
#define BACKLOG 10
int main(int argc, char **argv)
{
int sockfd[2],client_fd;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr; /* client socket info */
int sin_size;
int maxfd;
fd_set rfds;
int i;
if(argc != 3)
{
printf("Usage: %s <IP_1> <IP_2>\n", argv[0]);
return 1;
}
for(i = 0; i < 2; i++)
{
if ((sockfd[i] = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket error!"); exit(1);
}
else
{
printf("Create sockfd[%d] = %d\n", i, sockfd[i]);
}
}
// set the first Socket
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = inet_addr(argv[1]);
bzero(&(my_addr.sin_zero),8);
if (bind(sockfd[0], (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
perror("bind error!");
exit(1);
}
// set the second Socket
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = inet_addr(argv[2]);
bzero(&(my_addr.sin_zero),8);
if (bind(sockfd[1], (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
perror("bind error!");
exit(1);
}
for(i = 0; i < 2; i++)
{
if (listen(sockfd[i], BACKLOG) == -1) {
perror("listen error!");
exit(1);
}
}
if(sockfd[0] > sockfd[1])
maxfd = sockfd[0];
else
maxfd = sockfd[1];
while(1) {
FD_ZERO(&rfds);
FD_SET(sockfd[0], &rfds);
FD_SET(sockfd[1], &rfds);
printf("waiting client\n");
select(maxfd + 1, &rfds, NULL, NULL, NULL);
sin_size = sizeof(struct sockaddr_in);
if(FD_ISSET(sockfd[0], &rfds))
{
printf("sockfd[0](%s) is readable\n", argv[1]);
if ((client_fd = accept(sockfd[0], (struct sockaddr *)&remote_addr, (socklen_t *)&sin_size)) == -1) {
perror("accept error");
continue;
}
}
else if(FD_ISSET(sockfd[1], &rfds))
{
printf("sockfd[1](%s) is readable\n", argv[2]);
if ((client_fd = accept(sockfd[1], (struct sockaddr *)&remote_addr, (socklen_t *)&sin_size)) == -1) {
perror("accept error");
continue;
}
}
else
{
printf("select error\n");
continue;
}
printf("received a connection from %s:%d\n\n", (char *)inet_ntoa(remote_addr.sin_addr), ntohs(remote_addr.sin_port));
if (!fork()) { /* child process */
if (send(client_fd, "Hello, you are connected!\n", 26, 0) == -1)
perror("send error!");
close(client_fd);
exit(0);
}
close(client_fd);
}
}