Domanda

Lets say I have two different active network cards (A and B) on my system and also know their network interfaces information.

How would you connect to Card A for instance using FreePascal?

È stato utile?

Soluzione

I just compiled it and executed it, it seems to work. You just need to change the IP addresses and ports and add more error checking.

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>

#define MY_PORT 8564
#define THEIR_PORT 8090

int main()
{
    int     sockfd;
    struct sockaddr_in myaddr;
    struct sockaddr_in theiraddr;
    int res;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);

    memset(&myaddr, 0, sizeof(struct sockaddr_in));

    myaddr.sin_family = AF_INET;
    myaddr.sin_port = htons((unsigned short)MY_PORT);
    //myaddr.sin_addr = INADDR_ANY; //for any interface

    res = inet_pton(AF_INET, "127.0.0.1", &myaddr.sin_addr);

    if (1 == res)
    {
        res = bind(sockfd, (const struct sockaddr *)&myaddr, sizeof(struct sockaddr_in));

        if (0 == res)
        {
            printf("PASO-1\n");
            theiraddr.sin_family = AF_INET;
            theiraddr.sin_port = htons((unsigned short)THEIR_PORT);
            inet_pton(AF_INET, "10.0.2.78", &theiraddr.sin_addr);
            printf("PASO-2\n");
            connect(sockfd, (const struct sockaddr *)&theiraddr, sizeof(struct sockaddr_in));
        }
    }


   return 0;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top