0

I'm trying to get into socket programming with C and my problem is that no matter what I try I cannot get my client-server model to connect over the internet except through logging into my router and port forwarding the port I'm inputting in my program. Basically my server.c blocks and waits for a connection, then it sends the time of the server to the client once it connects. I've tried to open ports on both my machines like this:

sudo iptables -A INPUT -p tcp --dport 20001 -j ACCEPT

and I downloaded the iptables-persistent package that makes sure the rules stay on a reboot. iptables -L shows me that the ports are open on both machines, but the connection still times out. I know that somehow this is possible because Steam and Discord don't have to port forward anything and they still make it happen. I have a server at home so if the solution requires a 'middle man' server to facilitate a connection between two clients, then it won't be a problem for me. Also I am on two separate networks, so that's not the problem.

The server.c:

/* --- server.c --- */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>

int main(int argc, char *argv[])
{
    int listenfd = 0, connfd = 0;
    struct sockaddr_in serv_addr;

    char sendBuff[1025];
    time_t ticks;

    /* creates an UN-named socket inside the kernel and returns
     * an integer known as socket descriptor
     * This function takes domain/family as its first argument.
     * For Internet family of IPv4 addresses we use AF_INET
     */
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&serv_addr, '0', sizeof(serv_addr));
    memset(sendBuff, '0', sizeof(sendBuff));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(20001);

    /* The call to the function "bind()" assigns the details specified
     * in the structure 『serv_addr' to the socket created in the step above
     */
    bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

    /* The call to the function "listen()" with second argument as 10 specifies
     * maximum number of client connections that server will queue for this listening
     * socket.
     */
    listen(listenfd, 10);

    while(1)
    {
        /* In the call to accept(), the server is put to sleep and when for an incoming
         * client request, the three way TCP handshake* is complete, the function accept()
         * wakes up and returns the socket descriptor representing the client socket.
         */
        connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);

        /* As soon as server gets a request from client, it prepares the date and time and
         * writes on the client socket through the descriptor returned by accept()
         */
        ticks = time(NULL);
        snprintf(sendBuff, sizeof(sendBuff), "%.24s\r\n", ctime(&ticks));
        write(connfd, sendBuff, strlen(sendBuff));

        close(connfd);
        sleep(1);
    }
}

and client.c:

/* --- client.c --- */
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
    int sockfd = 0, n = 0;
    char recvBuff[1024];
    struct sockaddr_in serv_addr;

    if(argc != 2)
    {
        printf("\n Usage: %s <ip of server> \n",argv[0]);
        return 1;
    }

    memset(recvBuff, '0',sizeof(recvBuff));

    /* a socket is created through call to socket() function */
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("\n Error : Could not create socket \n");
        return 1;
    }

    memset(&serv_addr, '0', sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(20001);

    if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)
    {
        printf("\n inet_pton error occured\n");
        return 1;
    }

    /* Information like IP address of the remote host and its port is
     * bundled up in a structure and a call to function connect() is made
     * which tries to connect this socket with the socket (IP address and port)
     * of the remote host
     */
    if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
        printf("\n Error : Connect Failed \n");
        return 1;
    }

    /* Once the sockets are connected, the server sends the data (date+time)
     * on clients socket through clients socket descriptor and client can read it
     * through normal read call on the its socket descriptor.
     */
    while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0)
    {
        recvBuff[n] = 0;
        if(fputs(recvBuff, stdout) == EOF)
        {
            printf("\n Error : Fputs error\n");
        }
    }

    if(n < 0)
    {
        printf("\n Read error \n");
    }

    return 0;
}
9
  • 1
    If your server is running on port 20001 why is your client is trying to connect to port 42020? Aug 31, 2018 at 14:51
  • "I cannot get my client-server model to connect over the internet except through logging into my router and port forwarding the port I'm inputting in my program." That would be the case if your server is behind NAT, and there is nothing to be done about that.
    – Ron Maupin
    Aug 31, 2018 at 14:52
  • I was using two ports, 42020 and 20001. Apologies, the client.c was not updated on my server but was on the client itself which was connecting over 20001. I'll fix it.
    – bmw417
    Aug 31, 2018 at 14:59
  • And thanks Ron for that. My server is behind a regular home router with NAT enabled, but I have the option to turn it off. I'm not a networking guru like some of my other friends, but my server is currently serving OpenSSH on 22 for fileservice and Apache on 80/443 for my website. If I take my home network off NAT, will my connections be affected severely?
    – bmw417
    Aug 31, 2018 at 15:06
  • Can you use standard clients and servers to connect over your network? If not, socket programming is not the problem, your network is the problem. Steam and Discord clients are not servers. Try netcat. Aug 31, 2018 at 15:49

2 Answers 2

3

This line is saying what port you're connecting to on the server

serv_addr.sin_port = htons(42020);

change it to the same port number as the server and it should work just fine.

serv_addr.sin_port = htons(20001);
1
  • I did mess that up, apologies. I was using two ports, 42020 and 20001 to test. I pulled the old client.c from the server, but it was not updated to reflect a connection over 20001, of which my client was. Long story short, both my server and client were connecting over 20001 and I made the mistake of not updating my file
    – bmw417
    Aug 31, 2018 at 15:01
1
#include <stdio.h>
#include "http.h"

#define MAX 4096

int main()
{
    char s_msg[MAX], c_msg[MAX];
    printf("%d", strlen(s_msg));
    // Clean buffers:
    memset(s_msg,'\0',sizeof(s_msg));
    memset(c_msg,'\0',sizeof(c_msg));
 
    char *msg = "GET / HTTP/1.1\r\nUser-Agent: Hellothere\r\nHost: HOSTNAME\r\n\r\n";
 
    
    int soc = init_client();
 
    int con = connection("HOSTNAME",80);
 
 
    if(send(socket_desc, msg, strlen(msg), 0) < 0){
        printf("Unable to send message\n");
        return -1;
    }
 
 
    if (recv(socket_desc, c_msg , MAX, 0)<0)
    {
        printf("Failed to read from server\n");
        return -1;
    }
 
    printf("Recieved from server : %s\n",c_msg);
 
 
    return 0;
}

Using ngrok you need to use Host header

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.