How to fix my method that connects to a Server in C? - c

I am working on an assignment where I need to connect multiple clients on to one server. I am instructed to write a method that connects to. I tried several different ways of doing it, but it doesn't result in connecting. I need help in finding where the problem occurs and what I can do to fix it in order for the method to work in connecting to the server. I am working with sockets.
I am doing this on the client side since the client connects with the server. I keep resulting in the connection failing to connect with the server. Therefore, here is my code I have so far.
**
Client Side
**
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#define MAX 80
#define PORT 9064
#define SA struct sockaddr
int callServer(char *host, int portno) // connect to a server
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(&host);
servaddr.sin_port = htons(portno);
return connect(sockfd, (SA*)&servaddr, sizeof(servaddr)); // I return the an int.
}
int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
char thing[100] = "10.35.195.47";
// socket create and varification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// connect the client socket to server socket
if (callServer(thing, PORT) != 0) //connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0)
{
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
//callServer(thing, PORT);
// function for chat
func(sockfd);
// close the socket
close(sockfd);
return 0;
}
Now I tried several ways of doing this. This might not be the right approach but this is the 4th different approach I tried in creating this method. As of right now, I am unclear which one is the correct approach.
Server Side
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#define MAX 80
#define PORT 9064
#define SA struct sockaddr
int setupServerSocket(int portno) // setup a server socket
{
int serversocket, serv_bind;
struct sockaddr_in servaddr, cli;
serversocket = socket(AF_INET, SOCK_STREAM, 0);
if(serversocket < 0)
{
printf("Failed to create server\n");
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(portno); //port number given by user
// Binding newly created socket to given IP and verification
if ((bind(serversocket, (SA*)&servaddr, sizeof(servaddr))) != 0)
{
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
return serversocket;
}
int main()
{
int sockfd = setupServerSocket(9064), connfd, len;
struct sockaddr_in servaddr, cli;
// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0)
{
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0)
{
printf("server acccept failed...\n");
exit(0);
}
else
printf("server acccept the client...\n");
// Function for chatting between client and server
func(connfd);
// After chatting close the socket
close(sockfd);
}
Let me know.

Related

Client stuck when trying to connect via TCP/IP

I am new with socket programming and I have been following this tutorial: https://www.geeksforgeeks.org/tcp-server-client-implementation-in-c/
But it is only to use it in the local machine and my goal is to connect an embedded system with my computer (the computer is the server and the embedded system is the client).
To achieve the connection between the two systems, I have changed the servaddr.sin_addr.s_addr part of the client.c code, introducing the IP of the server in that line.
My server code (it gets compiled via gcc in the computer):
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
// Function designed for chat between client and server.
void func(int connfd)
{
char buff[MAX];
int n;
// infinite loop for chat
for (;;) {
bzero(buff, MAX);
// read the message from client and copy it in buffer
read(connfd, buff, sizeof(buff));
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n')
;
// and send that buffer to client
write(connfd, buff, sizeof(buff));
// if msg contains "Exit" then server exit and chat ended.
if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
}
// Driver function
int main()
{
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) {
printf("server accept failed...\n");
exit(0);
}
else
printf("server accept the client...\n");
// Function for chatting between client and server
func(connfd);
// After chatting close the socket
close(sockfd);
}
My client code (it gets compiled via gcc in the embedded system)
#include <arpa/inet.h> // inet_addr()
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h> // bzero()
#include <sys/socket.h>
#include <unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for (;;) {
bzero(buff, sizeof(buff));
printf("Enter the string : ");
n = 0;
while ((buff[n++] = getchar()) != '\n')
;
write(sockfd, buff, sizeof(buff));
bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff));
printf("From Server : %s", buff);
if ((strncmp(buff, "exit", 4)) == 0) {
printf("Client Exit...\n");
break;
}
}
}
int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("192.168.182.128");
servaddr.sin_port = htons(PORT);
// connect the client socket to server socket
if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr))
!= 0) {
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
// function for chat
func(sockfd);
// close the socket
close(sockfd);
}
The issue comes when I execute the client executable in the embedded system (after executing the server executable in the computer), as it gets stuck when trying to connect:
root#imx8mq-var-dart:~# ./client
Socket successfully created..
(infinitely here)
What am I doing wrong? Am I missing something?

socket binding failed (address already in use, even with SO_REUSEADDR)

I am working in a simple socket project. I would like to know:
why error messages appear before telnet localhost 5678?
why SO_REUSEADDR (between socket() and bind()) don't work, and what else I should try?
Code Output Message:
bind error
Error opening file: Address already in use
telnet localhost 5678
[+]Server Socket is created.
main.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#define BUFSIZE 1024 // Buffer Size
#define PORT 5678
int main() {
printf("telnet localhost 5678\n");
int rfd; // socket descriptor
int clientfd; // client descriptor
struct sockaddr_in client; // Client Socket address
socklen_t client_len; // Length of Client Data
char input[BUFSIZE]; // Client Data -> Server
int bytes_read; // Client Bytes
// 1. socket() = create a socket, SOCK_STREAM = TCP
rfd = socket(AF_INET, SOCK_STREAM, 0);
if (rfd < 0) {
fprintf(stderr, "socket error\n");
exit(-1);
}
printf("[+]Server Socket is created.\n");
// optional
int enable = 1;
if (setsockopt(rfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
fprintf(stderr, "setsockopt(SO_REUSEADDR) failed");
//Initialize the server address by the port and IP
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET; // Internet address family: v4 address
server.sin_addr.s_addr = INADDR_ANY; // Server IP address
server.sin_port = htons(PORT); // Server port
// 2. bind() = bind the socket to an address
int brt = bind(rfd, (struct sockaddr *) &server, sizeof(server));
if (brt < 0) {
int errnum;
errnum = errno;
fprintf(stderr, "bind error\n");
fprintf(stderr, "Error opening file: %s\n", strerror(errnum));
exit(-1);
}
printf("[+]Bind to port %d\n", PORT);
// 3. listen() = listen for connections
int lrt = listen(rfd, 50);
if (lrt < 0) {
printf("listen error\n");
exit(-1);
}
if (lrt == 0) {
printf("[+]Listening....\n");
}
// non-stop loop
while (1) {
// 4. accept() = accept a new connection on socket from client
clientfd = accept(rfd, (struct sockaddr *) &client, &client_len);
if (clientfd < 0) {
fprintf(stderr, "accept failed with error %d\n");
exit(-1);
}
printf("Client connected\n");
...
close(clientfd);
printf("Client disconnected\n");
}
close(rfd);
}
I'm assuming that you are using Linux. If you want to rebind to an address, you should use SO_REUSEPORT not SO_REUSEADDR. Name is really misleading. But make sure that you know how it works and whether you really want to use it or not.
You can check difference here: How do SO_REUSEADDR and SO_REUSEPORT differ?

TCP client server program using c in embedded board(arm64 arch)

I have TCP client-server c programs downloaded from github. The codes are working fine in host machine(x86). But when I have compiled and run the same programs for arm64 architecture board, client "connection refused" error is coming.
Test setup & procedure
Target board & host machine are connected using single Ethernet.
Static IPs are assigned such that both are in same network.
Target board & host machine both are able to PING their counterpart.
Server is running in arm64 target board & client in host machine.
Output:
Socket successfully created..
connection with the server failed...: Connection refused
Observation
When both client and server run in target board, connection is getting established.
The problem is encountered when TCP server & client are running in two different architectures.
Following are the codes
**// Server code
//#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#define MAX 80
#define PORT 10500
#define SA struct sockaddr
//print error message and exit process
void die(char *msg)
{
perror(msg);
exit(0); // EXIT_FAILURE
}
// Function designed for chat between client and server.
void func(int sockfd)
{
char buff[MAX];
int n;
// infinite loop for chat
for (;;) {
bzero(buff, MAX);
// read the message from client and copy it in buffer
read(sockfd, buff, sizeof(buff));
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n')
;
// and send that buffer to client
write(sockfd, buff, sizeof(buff));
// if msg contains "Exit" then server exit and chat ended.
if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
}
// Driver function
int main()
{
int sockfd, connfd;
unsigned int len;
struct sockaddr_in servaddr, cli;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0); // same as socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
if (sockfd == -1)
die("socket creation failed...");
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr)); // memset
// assign IP, PORT
servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); /* host-to-network endian */
servaddr.sin_port = htons(PORT); /* for listening */
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0)
die("socket bind failed...");
else
printf("Socket successfully binded..\n");
// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0) // max 5 connections
die("Listen failed...");
else
printf("Server listening for any client..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0)
die("server acccept failed...");
else
printf("server acccepted the client connection...\n");
// Function for chatting between client and server
func(connfd);
// After chatting close the socket
close(sockfd);
}**
//client code
// Write CPP code here
//#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
//#include <netinet/in.h>
#define MAX 80
#define PORT 10500
#define SA struct sockaddr
void die(char *msg)
{
perror(msg);
exit(0); // EXIT_FAILURE
}
void func(int sockfd)
{
char buff[MAX];
int n;
for (;;) {
bzero(buff, sizeof(buff));
printf("Enter the string for sending to server: ");
n = 0;
while ((buff[n++] = getchar()) != '\n')
;
write(sockfd, buff, sizeof(buff));
bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff));
printf("From Server : %s", buff);
if ((strncmp(buff, "exit", 4)) == 0) { // if Exit message received from Server
printf("Client Exit...\n");
break; //chat ended
}
}
}
int main()
{
int sockfd;
struct sockaddr_in servaddr;
// socket create and varification
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd == -1)
die("socket creation failed...");
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr)); // memset
// assign IP, PORT
servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT); /* for connecting */
// connect the client socket to server socket
if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0)
die("connection with the server failed...");
else
printf("connected to the server..\n");
// function for chat
func(sockfd);
// close the socket
close(sockfd);
}
This problem is perplexing. I am requesting to please help me to resolve the issue.

How do I store client's IPs in array in C (socket programming)

I have simple client/server program in socket in C. I use inet_ntoa that returns ip of clients connected to servers. I run a loop 2 times to connect 2 clients and store int in array of char.
The problem is that when I print the array it always gives the last ip added to the array. For example:
x.x.x.x connected
y.y.y.y connected
The array prints y.y.y.y two times
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
// Driver function
int main() {
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
struct sockaddr_in addr_remote;
char * ips[2];
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero( & servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA * ) & servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
// Now server is ready to listen and verification
int i = 0;
for (i = 0; i < 2; i++) {
if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA * ) & addr_remote, & len);
if (connfd < 0) {
printf("server acccept failed...\n");
exit(0);
}
else
printf("server acccept the client...\n");
// Function for chatting between client and server
// func(connfd);
//printf( " Welcome %s " , inet_ntoa(addr_remote.sin_addr));
ips[i] = inet_ntoa(addr_remote.sin_addr);
}
for (i = 0; i < 2; i++) {
printf("%s", ips[i]);
}
// After chatting close the socket
close(sockfd);
}
You have to allocate Your own char array for IP and copy it from static buffer returned by inet_ntoa(). Simple example:
char ips[2][20];
...
strcpy(ips[i], inet_ntoa(...))
EDIT: The point is, that the inet_ntoa() function stores it's result to it's internal, statically allocated, buffer and returns just a pointer to it, which is constant. So Your ip[0] and ip[1] both contain the same pointer, which points to the last IP obtained from inet_ntoa().

How can i add Scanner Port

i have code create with c and socket of display to adress conecting in my server , now i need to do some code for scanner port in one of there adresses, the input is start port and end port and the server scan ports who connecting in one of adress local
Please i neeeeeeeeeeeed Help
someone who help me
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
// Driver function
int main()
{
int sockfd, connfd, len ,start , end;
struct sockaddr_in servaddr, cli;
struct sockaddr_in addr_remote;
char ips[2][20];
char hostname[30];
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
for(int i=0;i<2;i++){
connfd = accept(sockfd, (SA*)&addr_remote, &len);
if (connfd < 0) {
printf("server acccept failed...\n");
exit(0);
}
else
printf("server acccept the client...\n");
strcpy(ips[i], inet_ntoa(addr_remote.sin_addr));
}
// Display Ip
for(int i=0;i<2;i++){
printf("%s \n",ips[i]);}
// Scan PORT
//Get the hostname to scan
printf("Enter hostname or IP : ");
gets(hostname);
//Get start port number
printf("Enter start port number : ");
//To Handle the Input
int data;
data = scanf("%d",&start);
//Get end port number
printf("Enter end port number : ");
int data2 = scanf("%d" , &end);
// After Display close the socket
close(sockfd);
}

Resources