Beej's Guide Network to Programming series serialization 11

Source: Internet
Author: User
Tags telnet program

5.4. connect () --- hey, are you?
Now we assume you are a telnet program. Your USER command you get the file descriptor of the socket. You followed the command to call socket (). Next, your user will tell you to connect to "10.12.110.57" through port 23 (Standard telnet port ". What do you do? Fortunately, you are reading the connect ()-how to connect to a remote host chapter. You don't want to disappoint your users.

The following is his prototype:

# Include <sys/types. h>

# Include <sys/socket. h>

 

Connect (intsockfd, struct sockaddr * serv_addr, int addrlen );

 

Sockfd is the socket file descriptor returned by the system to call socket. Serv_addr is a struct sockaddr that contains IP addresses and ports. Addrlen is the length of this structure.

We still use the parameters returned by the getaddrinfo () function.

The following example shows how to connect to port 3490 of www.2cto.com:

 

Struct addrinfohints, * res;

Int sockfd;

 

Memset (& hints, 0, sizeof (hints ));

Hints. ai_family = AF_UNSPEC;

Hints. ai_socktype = SOCK_STREAM;

 

Getaddrinfo (www.2cto.com, "3490", & hints, & res );

 

 

// Make a socket:

Sockfd = socket (res-> ai_family, res-> ai_socktype, res-> ai_protocol );

 

// Connect!

Connect (sockfd, res-> ai_addr, res-> addrlen)

 

At the same time, you may see that I did not call bind (). Because I don't care about the local port number. I only care about where I am going. The kernel will select an appropriate port number for me, and the information will be automatically obtained from the locations we connect. No worries.

From the column xiaobin_HLJ80

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.