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 套接字: connect 方法

From Wiki
Jump to: navigation, search
Article Metadata

文章
dougcn 在 24 Jun 2008 创建
最后由 hamishwillee 在 15 Dec 2011 编辑

Open C 套接字: connect 方法

connect方法初始化socket连接。

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

s参数是一个套接字。如果是类型SOCK_DGRAM,这个调用指定待联系的对等方; 其地址是数据报要发送到的那个地址,和待接收数据报的唯一地址。

若套接字是SOCK_STREAM类型,这个调用尝试连接到另一个套接字。别个套接字以name指定,一个在套接字通讯空间的地址。一般来说,流套接字可以

一次性成功连接;而数据报套接字可能使用connect多次以便改变它们的联系。数据报套接字可能通过连接到一个无效地址,比如空地址,而断开联系。

如果成功connect()函数返回值0;否则返回值-1且设置全局变量errno指示出错误。

下面的代码片段演示了connect方法的用法:

#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);
}

内部链接

Internal Links

This page was last modified on 15 December 2011, at 05:40.
242 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.

×