Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Open C Sockets: connect method

From Wiki
Jump to: navigation, search
Article Metadata
Article
Created: polaka_sr (17 Jun 2008)
Last edited: hamishwillee (08 Feb 2012)

The connect method initiates a connection on a socket.

int connect (int s, const struct sockaddr *name, socklen_t namelen);

The s argument is a socket. If it is of type SOCK_DGRAM, this call specifies the peer with which the socket is to be associated; this address is that to which datagrams are to be sent, and the only address from which datagrams are to be received.

If the socket is of type SOCK_STREAM, this call attempts to make a connection to another socket. The other socket is specified by name, which is an address in the communications space of the socket. Each communications space interprets the name argument in its own way. Generally, stream sockets may successfully connect only once; datagram sockets may use connect multiple times to change their association. Datagram sockets may dissolve the association by connecting to an invalid address, such as a null address.

The connect() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Following code snippet shows the usage of connect method:

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void Connect()
{
struct sockaddr_in serv_addr;
int sock_fd;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
serv_addr.sin_port = htons(5000);
sock_fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
connect(sock_fd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
 
close(sock_fd);
}

Wiki Links

Open C Sockets Overview

This page was last modified on 8 February 2012, at 02:42.
43 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×