5.2 socket --- 获得文件描述符

原文:https://beej.us/guide/bgnet/html/#socket

 

5.2 socket --- 获得文件描述符

       我不想长篇大论---我要谈的调用系统函数socket()。下面是他的原型:

#include<sys/types.h>
#include<sys/socket.h>


int socket(int domain, int type, int protocol);
  • domain  可以选择PF_INET或者PF_INET6;
  • type   可以选择SOCK_STREAM或者SOCK_DGRAM;
  • protocol 设置为0,或者你可以调用getprotobyname()来查找你想要的协议,“tcp”或“UDP”     

       它曾经是人们将这些值进行硬编码,你也可以这么做。

       译者注:SOCK_STREAM等同于TCP;SOCK_DGRAM等同于UDP。

 

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

       译者注:他们其实是等同的,

有兴趣的读者可以看《Unix Network Programming》第一卷中第四章第2节中的“AF_xxx Versus PF_xxx”

 

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

int s;
struct addrinfo hints, *res;

// do the lookup
// [pretend we already filled out the "hints" struct]
getaddrinfo("www.example.com", "http", &hints, &res);

// again, you should do error-checking on getaddrinfo(), and walk
// the "res" linked list looking for valid entries instead of just
// assuming the first one is good (like many of these examples do).
// See the section on client/server for real examples.

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

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

    好,好,好!但是使用这样的方式有什么益处吗?

    答案就是:简洁!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值