Connecting to a port using TCP using C

I am 99% new to sockets and any network programming, so please bear with me.

I am trying to connect to a port (2111 in this case) on my local computer (192.168.0.1). From there I plan to send and receive basic information, but this is the next day.

I have currently tried this:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv)
{
    int sd;
    int port;
    int start;
    int end;
    int rval;
    struct hostent *hostaddr;
    struct sockaddr_in servaddr;

    start = 2111;
    end   = 2112;
    for(port = start; port <= end; port++)
    {
        sd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
        if(sd == -1)
        {
            perror("Socket()\n");
            return (errno);
        }

        memset(&servaddr, 0, sizeof(servaddr));

        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(port);

        hostaddr = gethostbyname("192.168.0.1");

        memcpy(&servaddr.sin_addr, hostaddr->h_addr, hostaddr->h_length);

        rval = connect(sd, (struct sockaddr *)&servaddr, sizeof(servaddr));
        if(rval == -1)
        {
            printf("Port %d is closed\n", port);
            close(sd);
        }
        else printf("Port %d is open\n", port);

        close(sd);
    }

    return 0;
}

However, my call connect()freezes for about 90 seconds and then returns -1.

The device is directly connected to the Mac Mini's Ethernet port, and the manufacturer has confirmed that port 2111 or 2112.

What am I doing wrong? Also, can it be in ELI5 format (explain how to me 5)? I am much better with examples.

+4
source share
2

connect() , SYN-, TCP . :

  • , SYN + ACK, ACK, - connect() .
  • , ICMP- , , , connect() ECONNREFUSED ( ). , (RTT), , .
  • TCP SYN + ACK TCP, ICMP-, , SYN - SYN , -, , connect() ETIMEDOUT. 1-2 , TCP.

№ 3. :

  • SYN , , - , .
  • SYN + ACK ICMP, , - , .
  • /
  • - SYN + ACK ICMP

ethernet, # 1 # 2. # 4 , , 3 .

- ethernet ( Ethernet), Wi-Fi, loopback, VPN- .. , , , , . ( ), .

, , . IP- , , . , , IP 54.xyz, IP 192.168.1.1, , , " , 192.168.0.0/16, NIC 2 , NIC 1". , , , bind() connect().

, ?

, 192.168.0.1 , . ? DHCP-, ? IP-?

, . IP-, , Mac , , , . Mac OS X route(8), reset ; . IP-, Ethernet, .

bind() connect() , , , . , curl(1) --interface <name>, .

+6

, connect() ( errno ).

, - - . . connect(), select() .

SPOILER ConnectWithTimeout() Linux

+1

Source: https://habr.com/ru/post/1548545/


All Articles