设为首页 加入收藏

TOP

Beej’s Guide Network to Programming 系列连载09
2014-11-24 00:33:15 来源: 作者: 【 】 浏览:49
Tags:Beej Guide Network Programming 系列 连载

5.2. socket() ---获得文件描述符
我不想长篇大论---我要谈的调用系统函数socket()。下面是他的原型:

#include

#include

int socket(intdomain, int type, int protocol);

但是这些参数干什么的呢?他们允许你使用哪种套接字(IPv4还是IPv6;TCP还是UDP)。

它曾经是人们将这些值进行硬编码,你也可以这么做。(domain可以选择PF_INET或者PF_INET6;type可以选择SOCK_STREAM或者SOCK_DGRAM;protocol设置为0,或者你可以调用getprotobyname()来查找你想要的协议,“tcp”或“UDP” 。)

译者注:SOCK_STREAM等同于TCP;SOCK_DGRAM等同于UDP。所以你不用费二遍事再作一次J

(编者在这儿又叙述了一下PF_*与AF_*的一些关系)

译者注:他们其实是等同的,有兴趣的读者可以看《UnixNetwork Programming》第一卷中第四章第2节中的“AF_xxxVersus PF_xxx”

你真正要做的是把调用getaddrinfo()得到的结果值,直接给socket()函数使用像下面这样:

int s;

struct addrinfohints, *res;

// do the lookup

// [pretend wealready filled out the “hints” struct]

getaddrinfo(www.example.com, “http”, &hints,&res);

// [again, youshould do error-checking on getaddrinfo(), and walk

// the “res”linked list looking for valid entries instead of just

// assuming thefirst one is good (like many of these example do.)

// See the sectionon client/server for real examples.]

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

socket()函数只是简单地返回给你一个套接字描述符,以供其后的其它系统函数使用;或者返回-1错误。全局变量errno是设置错误值的。(errno详见man文档)

好,好,好!但是使用这样的方式有什么益处吗?答案就是:简洁!

摘自 xiaobin_HLJ80的专栏
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇模板应用(1) 浅析API的设计 下一篇Beej’s Guide Network to Progra..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: