Specifying port number on client side - c

How can I make sure that my client uses a particular port to connect to server in a typical server client program. Like in server side we are using a port number in bind system call and then listen on that particular port, is there any way we can specify the port number on the client side and uses the same port to connect to server. Server = 3456 ,
Client = 7834 ( I want to specify this port number so that client uses 7834 for connection). I am trying in C and Unix platform.

You do this on the client side exactly as you do it on the server side - using bind(). It's just that the client calls connect() after bind() instead of calling listen().
Note that you will only be able to run one instance of the client on each machine if you do this, and your server might see a different client port anyway if there are network middleboxes using address translation between the client and server.

The client program can set sockaddr...sin_port and then call bind() before connecting and it will get, subject to availability, the requested outgoing port.
The server can verify this port is set manually by calling getpeername() and checking it.
As others have said though, you dont really need to set the outgoing port usually, unless you have something weird going on, or specific requirements.

It's similar with server side, usually we do
local_addr.sin_port = htons(INADDR_ANY);
because port number is not important. Instead, you can use
local_addr.sin_port = htons(src_port); /Use the src_port as you like
And then call bind

Here is a working solution that runs in debian linux on the ts-7500 sbc. it should port pretty easy. This solution also looks up the ip address of the client machine automatically.
/*dl_senderprog.c - debian linux send to server a client, datagram*/
/***********************************************************************
140203 lets see if we can bind to a port
ts7500:/var/www/jon/uvir_sensor_lab/source/socket#
ts7500:/var/www/jon/uvir_sensor_lab/source/socket# vi senderprog_bind.c
ts7500:/var/www/jon/uvir_sensor_lab/source/socket# gcc -g senderprog_bind.c -o senderprog_bind
ts7500:/var/www/jon/uvir_sensor_lab/source/socket# ./senderprog_bind
Sender:Client-Usage: ./senderprog_bind <hostname> <message>
ts7500:/var/www/jon/uvir_sensor_lab/source/socket#
ts7500:/var/www/jon/uvir_sensor_lab/source/socket#
ts7500:/var/www/jon/uvir_sensor_lab/source/socket# ./senderprog_bind 10.0.1.26 "dot,33,22"
MY IP address:10.0.1.242: on port: 1043
Sender: Client-gethostname() is OK...
Sender: Client-socket() sockfd is OK...
Sender: Using port: 14950
Sender: Client-sendto() is OK...
Sender: sent 9 bytes to 10.0.1.26
Sender: Client-sockfd successfully closed!
ts7500:/var/www/jon/uvir_sensor_lab/source/socket#
ts7500:/var/www/jon/uvir_sensor_lab/source/socket#
ts7500:/var/www/jon/uvir_sensor_lab/source/socket# # it worked!!!!!
ts7500:/var/www/jon/uvir_sensor_lab/source/socket#
***********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/ioctl.h>
#include <net/if.h>
/* the port users will be connecting to 14950 is the port on the windows machine
that I have the server running on */
#define TOPORT 14950
#define MYPORT 1043
void my_ip( char *myniccard, char *myipaddr) {
int fd;
struct ifreq ifr;
myipaddr[0]=0;
fd = socket(AF_INET, SOCK_DGRAM, 0);
/* I want to get an IPv4 IP address */
ifr.ifr_addr.sa_family = AF_INET;
/* I want IP address attached to "eth0" */
//strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
strncpy(ifr.ifr_name, myniccard, IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
/* display result */
sprintf(myipaddr,"%s"
, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
printf("MY IP address:%s: on port: %d\n", myipaddr, MYPORT);
} // my_ip
int main(int argc, char *argv[ ])
{
int sockfd;
/* connectors address information */
struct sockaddr_in their_addr;
struct sockaddr_in localaddr;
char myipaddressm[22]; //buffer for ip address
char *myniccardm ="eth0"; // check with ipconfig for correct ethernet port
struct hostent *he;
int numbytes;
if (argc != 3) {
fprintf(stderr, "Sender:Client-Usage: %s <hostname> <message>\n", argv[0]);
exit(1);
}
my_ip(myniccardm, myipaddressm);
/* get the host info */
if ((he = gethostbyname(argv[1])) == NULL) {
perror("Sender: Client-gethostbyname() error lol!");
exit(1);
}
else
printf("Sender: Client-gethostname() is OK...\n");
if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror("Sender: Client-socket() error lol!");
exit(1);
}
else
printf("Sender: Client-socket() sockfd is OK...\n");
// Bind to a specific network interface
// (this is unusual, as you normally do not want a specific
// port for the client, but we have a specific server in
// this case that will not accept connects unless its on
// a specific port )
localaddr.sin_family = AF_INET;
localaddr.sin_addr.s_addr = inet_addr(myipaddressm);
localaddr.sin_port = htons(MYPORT); // Any local port will do
bind(sockfd, (struct sockaddr *)&localaddr, sizeof(localaddr));
/* host byte order */
their_addr.sin_family = AF_INET;
/* short, network byte order */
printf("Sender: Using port: %d\n",TOPORT);
their_addr.sin_port = htons(TOPORT);
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
/* zero the rest of the struct */
memset(&(their_addr.sin_zero), '\0', 8);
if((numbytes = sendto(sockfd, argv[2],
strlen(argv[2]),
0,
(struct sockaddr *)&their_addr,
sizeof(struct sockaddr))) == -1) {
perror("Sender: Client-sendto() error lol!");
exit(1);
}
else
printf("Sender: Client-sendto() is OK...\n");
printf("Sender: sent %d bytes to %s\n", numbytes, inet_ntoa(their_addr.sin_addr));
if (close(sockfd) != 0)
printf("Sender: Client-sockfd closing is failed!\n");
else
printf("Sender: Client-sockfd successfully closed!\n");
return 0;
}//main
/*******************************************EOF***********************/

Related

Random port connection while portscan

I've made a very basic port-scan program in C to scan a port range. Here it is:
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define HOST "127.0.0.1"
#define PORT 4444
int createConnection(const char *host[], const int port)
{
struct sockaddr_in addr;
int sock = 0;
int ret;
struct sockaddr_in server_addr;
if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
printf("Error %d socket creating.\n", sock);
return -1;
}
else
{
memset(&server_addr, '0', sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
ret = inet_pton(AF_INET, host, &server_addr.sin_addr);
if (ret <= 0)
{
printf("Error %d unsuported address: %d\n", ret);
return -2;
}
else
{
ret = connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (ret < 0)
{
//printf("[-] Port %d closed.\n", port);
close(sock);
return 1;
}
else
{
printf("[+] Port %d open.\n", port);
close(sock);
return 0;
}
}
}
}
int main(int argc, const char *argv[])
{
for (int i = 1; i < 65536; i++)
{
createConnection("127.0.0.1", i);
}
}
As you can see in the for loop, it scans from port 1 to port 65535. The problem is that when I start it, I get this output:
[+] Port 42178 open.
[+] Port 48650 open.
[+] Port 60078 open.
The "open ports" always change, but are always superior to 40000. But, I checked with netstat -tulpn, only my port 68 is open for the dhclient, which is UDP and not TCP. Why does it say that I have open ports ?
I suspect you're running into your open socket source ports while scanning.
TCP connections have a source port. If one is not assigned to a socket (via bind), then the kernel assigns an ephemeral port (in the high range) to the socket when you call connect, before the SYN is sent.
Since you are connecting your sockets to your local machine, as you loop through the destination ports, it is possible that the kernel will assign a random ephemeral source port that happens to match the same destination port to which you're about to connect.
See:
Linux/Unix Socket Self-connection
Socket getting created with same IP and port on local host

Checking for open ports on a remote server using sockets hangs when the port is closed, C

I wrote a simple application which connects to a given server on a given port. When the port is open, everything is ok, I got the message about the established connection. However, when the port is closed, nothing happens, my program does not show me the information about it.
I test my program using my remote server accessible via the Internet. How can I improve this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main(int argc, char **argv) {
char * ip_addr;
int port;
int sockfd;
struct sockaddr_in server_addr;
if (argc != 3)
{
fprintf(stderr,"Usage: ./canconnect ip port\n");
exit(1);
}
ip_addr = argv[1];
port = atoi(argv[2]);
if (port <= 0)
{
fprintf(stderr,"error: invalid port\n");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
inet_aton(ip_addr, &server_addr.sin_addr);
if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
{
perror("connect");
printf("Port %d is closed on server %s.\n", port, ip_addr);
exit(1);
}
else
{
printf("Connection established. Port %d is open on server %s.\n", port, ip_addr);
}
close(sockfd);
return 0; }
Given that the program actually prints some data after some time, it's most certainly has to do with timeout.
In order to finally decide that the host or the port is unreadable or the connection couldn't be established for any other reason, connect performs several attempts to connect and returns an error after a certain amount of time - the timeout.
The value of timeout can be changed to any value you want using setsockopt:
struct timeval timeout;
timeout.tv_sec = 3; // wait for three seconds
timeout.tv_usec = 0;
// set up receive timeout
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
sizeof(timeout)) < 0)
printf("[!] setsockopt failed\n");
If the remote server is reachable, but neither accepts nor refuses the connection, then connect() will block until the network connection attempt times out. As the Linux manual page for connect(2) puts it:
Note that for IP sockets the timeout may be very long when syncookies are enabled on the server.
Indeed, it is a well-known defense against port scans to attempt to elicit that behavior intentionally. You might be able to get quicker failures by using setsockopt() to set a receive timeout, but the docs are inconsistent on whether that will work for connect().

How to give to a client specific ip address in C

I am trying to implement a simple client and server in C and I can't find online an example how to set a specific IP address to the client. This is what I got so far:
sockfd = socket(PF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
<some code to handle error>
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(<addressOfTheServer>);
address.sin_port = htons(<portToConnectToServer>);
len = sizeof(address);
int result = connect(sockfd, (struct sockaddr *)&address, len);
On the server side I check for the client IP Address and I always get 127.0.0.1
I want to change it something different.
If you want your client to connect using a specific network interface (say, because you have multiple network cards), then you first need to call bind(2) on that interface's IP address before connecting. For example, if you have two network interfaces with IP addresses 192.168.1.100 and 10.101.151.100, then to connect using the 192.168.1.100 address you could do this:
// Error checking omitted for expository purposes
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
// Bind to a specific network interface (and optionally a specific local port)
struct sockaddr_in localaddr;
localaddr.sin_family = AF_INET;
localaddr.sin_addr.s_addr = inet_addr("192.168.1.100");
localaddr.sin_port = 0; // Any local port will do
bind(sockfd, (struct sockaddr *)&localaddr, sizeof(localaddr));
// Connect to the remote server
struct sockaddr_in remoteaddr;
remoteaddr.sin_family = AF_INET;
remoteaddr.sin_addr.s_addr = inet_addr(server_ip);
remoteaddr.sin_port = htons(server_port);
connect(sockfd, (struct sockaddr *)&remoteaddr, sizeof(remoteaddr));
OK so I put the solution together with getting the ip address off of the computer as well:
/*dl_senderprog.c - debian linux send to server a client, datagram*/
/***********************************************************************
140203 lets see if we can bind to a port
ts7500:/var/www/jon/uvir_sensor_lab/source/socket#
ts7500:/var/www/jon/uvir_sensor_lab/source/socket# vi senderprog_bind.c
ts7500:/var/www/jon/uvir_sensor_lab/source/socket# gcc -g senderprog_bind.c -o senderprog_bind
ts7500:/var/www/jon/uvir_sensor_lab/source/socket# ./senderprog_bind
Sender:Client-Usage: ./senderprog_bind <hostname> <message>
ts7500:/var/www/jon/uvir_sensor_lab/source/socket#
ts7500:/var/www/jon/uvir_sensor_lab/source/socket#
ts7500:/var/www/jon/uvir_sensor_lab/source/socket# ./senderprog_bind 10.0.1.26 "dot,33,22"
MY IP address:10.0.1.242: on port: 1043
Sender: Client-gethostname() is OK...
Sender: Client-socket() sockfd is OK...
Sender: Using port: 14950
Sender: Client-sendto() is OK...
Sender: sent 9 bytes to 10.0.1.26
Sender: Client-sockfd successfully closed!
ts7500:/var/www/jon/uvir_sensor_lab/source/socket#
ts7500:/var/www/jon/uvir_sensor_lab/source/socket#
ts7500:/var/www/jon/uvir_sensor_lab/source/socket# # it worked!!!!!
ts7500:/var/www/jon/uvir_sensor_lab/source/socket#
***********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/ioctl.h>
#include <net/if.h>
/* the port users will be connecting to 14950 is the port on the windows machine
that I have the server running on */
#define TOPORT 14950
#define MYPORT 1043
void my_ip( char *myniccard, char *myipaddr) {
int fd;
struct ifreq ifr;
myipaddr[0]=0;
fd = socket(AF_INET, SOCK_DGRAM, 0);
/* I want to get an IPv4 IP address */
ifr.ifr_addr.sa_family = AF_INET;
/* I want IP address attached to "eth0" */
//strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
strncpy(ifr.ifr_name, myniccard, IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
/* display result */
sprintf(myipaddr,"%s"
, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
printf("MY IP address:%s: on port: %d\n", myipaddr, MYPORT);
} // my_ip
int main(int argc, char *argv[ ])
{
int sockfd;
/* connectors address information */
struct sockaddr_in their_addr;
struct sockaddr_in localaddr;
char myipaddressm[22]; //buffer for ip address
char *myniccardm ="eth0"; // check with ipconfig for correct ethernet port
struct hostent *he;
int numbytes;
if (argc != 3) {
fprintf(stderr, "Sender:Client-Usage: %s <hostname> <message>\n", argv[0]);
exit(1);
}
my_ip(myniccardm, myipaddressm);
/* get the host info */
if ((he = gethostbyname(argv[1])) == NULL) {
perror("Sender: Client-gethostbyname() error lol!");
exit(1);
}
else
printf("Sender: Client-gethostname() is OK...\n");
if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror("Sender: Client-socket() error lol!");
exit(1);
}
else
printf("Sender: Client-socket() sockfd is OK...\n");
// Bind to a specific network interface
// (this is unusual, as you normally do not want a specific
// port for the client, but we have a specific server in
// this case that will not accept connects unless its on
// a specific port )
localaddr.sin_family = AF_INET;
localaddr.sin_addr.s_addr = inet_addr(myipaddressm);
localaddr.sin_port = htons(MYPORT); // Any local port will do
bind(sockfd, (struct sockaddr *)&localaddr, sizeof(localaddr));
/* host byte order */
their_addr.sin_family = AF_INET;
/* short, network byte order */
printf("Sender: Using port: %d\n",TOPORT);
their_addr.sin_port = htons(TOPORT);
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
/* zero the rest of the struct */
memset(&(their_addr.sin_zero), '\0', 8);
if((numbytes = sendto(sockfd, argv[2],
strlen(argv[2]),
0,
(struct sockaddr *)&their_addr,
sizeof(struct sockaddr))) == -1) {
perror("Sender: Client-sendto() error lol!");
exit(1);
}
else
printf("Sender: Client-sendto() is OK...\n");
printf("Sender: sent %d bytes to %s\n", numbytes, inet_ntoa(their_addr.sin_addr));
if (close(sockfd) != 0)
printf("Sender: Client-sockfd closing is failed!\n");
else
printf("Sender: Client-sockfd successfully closed!\n");
return 0;
}//main
/*******************************************EOF***********************/
I've run this on my debian linux embedded arm ts-7500 single board computer.

TCP: Establish a TCP connection

I've read many examples on networking with C and I'm stuck. I can see that the TCP packets with the SYN flag are on the wire (with wireshark), but the receiving end (I've set up a virtual machine for testing purposes) sends nothing back, not even RST.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <strings.h>
int establish_tcp(int port) {
char *ip = "10.0.2.15"; /* Virtual Machine */
struct sockaddr_in sockaddrin;
struct hostent *host;
int sock;
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == -1) {
fprintf(stderr, "Socket Error\n");
exit(1);
}
sockaddrin.sin_family = AF_INET;
host = gethostbyname(ip);
if(host == NULL) {
fprintf(stderr, "%s unknown host.\n", ip);
exit(2);
}
/* copies the internet address into the struct */
bcopy(host->h_addr, &sockaddrin.sin_addr, host->h_length);
/* specify port (used by TCP a layer above */
sockaddrin.sin_port = port;
/* try to connect */
return connect(sock, (struct sockaddr*) &sockaddrin, sizeof(struct sockaddr_in));
}
int main(void) {
printf("status: %i\n", establish_tcp(80));
return 0;
}
It takes a while until the packets are timed out and -1 is returned as status code. How can it happen that the target machine doesn't send a reply? What have I overlooked?
I think I've figured out that it is not a setup problem. I'm running Ubuntu 12.04. The virtual machine is a Debian Wheezy, I check its IP with ifconfig. I tried if the machine is reachable with telnet.
To escape issues which might be related to Virtual Box I tried to replace the IP with the one of Google, yielding the same results.
The problem most likely is this:
sockaddrin.sin_port = port;
The port number has to be in network byte order, which is different from the native byte order in x86 and x86_64 machines.
Change to:
sockaddrin.sin_port = htons(port);

C, Sockets: Connection Refused error

I've a data acquisition module from which I would like to collect data from the Ethernet port. I'm getting there in steps, currently I would like to just connect to server from a client. I've used Beej's guide to get the basic C code. But I just keep getting this connect error connect: Connection refused.
This is what I do:
The network IP mentioned here is STATIC IP which I have configured.
The port number is set to 50000 on Server side and from the client side I connect to this IP on the port 50000.
I build and run the server side application and then try to connect to it by running a client side application.
One doubt about server side, server side application returns before I start the client side application, so should I keep it running (while(1);) so that I can connect to it from the client side?
What's going wrong am I forgetting something here? Help!
I'm pasting the very slightly modified (IP and port numbers are different) Beej's C code for Server side and Client side here:
Server.c
/*
** server.c
*/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
// code for a server waiting for connections
// namely a stream socket on port 3490, on this host's IP
// either IPv4 or IPv6.
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // use AF_INET6 to force IPv6
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP address
if ((rv = getaddrinfo(NULL, "50000", &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
exit(1);
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1)
{
perror("socket");
continue;
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
close(sockfd);
perror("bind");
continue;
}
break; // if we get here, we must have connected successfully
}
if (p == NULL)
{
// looped off the end of the list with no successful bind
fprintf(stderr, "failed to bind socket\n");
exit(2);
}
freeaddrinfo(servinfo); // all done with this structure
}
Client.c
/*
** client.c
*/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
// code for a client connecting to a server
// namely a stream socket to www.example.com on port 80 (http)
// either IPv4 or IPv6
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // use AF_INET6 to force IPv6
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo("192.168.2.4", "50000", &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
exit(1);
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1)
{
perror("socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
close(sockfd);
perror("connect");
continue;
}
break; // if we get here, we must have connected successfully
}
if (p == NULL)
{
// looped off the end of the list with no connection
fprintf(stderr, "failed to connect\n");
exit(2);
}
freeaddrinfo(servinfo); // all done with this structure
}
Your server code is missing listen() and accept() code to "wait" for a connection by calling listen() and then performing an accept() to accept new connections. Doesn't the example you are using show how to do that? Typically you will also fork a new thread for each new connection.
See http://www.linuxhowtos.org/C_C++/socket.htm for more information.
Here's a link to a more complete implementation: http://www.thegeekstuff.com/2011/12/c-socket-programming/
Yes, you need to keep the server program running. In your server program you have created the socket using socket() and bound to an address bind(), now you need to start listening for incoming connections. This is done with the listen() call. Once the socket is listening for incoming connections you have to use the accept() call to actually accept a connection and get the socket for communication with that particular client.
As a quick example, after the freeaddrinfo you could add the following code:
listen(sockfd, 8); /* allow up to 8 pending connections, i.e. created but not accepted */
while (1) {
int clientfd;
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(struct sockaddr_in);
clientfd = accept(sockfd, &client_addr, &client_addr_len);
/* communicate with client by send()/recv() or write()/read() on clientfd */
close(clientfd);
}
This code has the deficiency that only one client at a time is handled. There are a few ways to handle multiple simultaneous clients: multiple processes using fork(), multiple threads, or polling. Each of these approaches are, in my opinion, outside the scope of this question.
Please look at your Server.c file: it does not call listen() at all!
If the targeted server does not listen on the specified port, then it would return RST packet upon receiving SYN packet from the client, so connect() would return with "Connection refused".
Normal flow of functions at server side is socket -> bind -> listen -> accept :
getaddrinfo();
socket();
bind();
listen();
/* accept() goes here */
Please refer to https://beej.us/guide/bgnet/html/multi/syscalls.html#listen
I was getting the error "connection refused" due to not having the entry of remote host in /etc/hosts file. Entry should be present both side. In Client machines /etc/hosts, there should be a entry of server machine and vice versa in below pattern.
<ip address> <hostname with domain> <alias hostname>
This solved the error which i was in getaddrinfo() function.

Resources