Daily Archives: 2017-10-31

一些网络编程所需头文件/函数

建立tcp/ip连接首先需要新建一个socket

在c中,要使用socket(int,int,int)函数新建socket,该函数定义在sys/socket.h头文件下还有一直困扰我很久的在一些头文件中sin的意思终于被我搞明白了….sin不是三角函数,而是Socket INternet hhhh

然而去Google搜了一下,好像大家对那些头文件中奇怪的名字好像也不是很理解,比如说address_in 中的in….大概是只可意会不可言传吧hh

还有定义在<arpa/inet.h>中的htons(unsigned int)负责将参数转换为网络字节顺序,至于要在设么时候转换成网络字节顺序,详见这篇文章

You should generally always use them on all raw integers sent across the network…
If you’ve got a 16-bit int, you use htons() on data you’re about to send, and ntohs()
on data you’ve received; if you’ve got a 32-bit int, you use htonl()/ntohl()…  (Sadly,
there’s no standard 64-bit versions yet, so if you’ve got a 64-bit int, you kind of have
to roll your own…)  If you’ve got anything other than a raw int of some kind, you don’t
use them…  Ie: single characters or strings of multiple characters never need any
such trickery done to them…  And, you only need to do it on ints that actually are
transmitted across the network…  (This includes ones you actually send yourself, as
well as ones sent for you by the TCP/IP stack in packet headers and such…  Eg: raw
IPs, port numbers, etc…)

The reason this is necessary is due to different machines having different native ideas
about how to layout integer values in memory…  Technically, if you were sending to a
host that was the same architecture as you (or, at least the same endianness), you
wouldn’t have to bother converting to/from network order on any ints you send,
since both ends would agree on how to interpret them…  But, if you’re coding
something intended to work generically, communicating with any machine on the
Net, you have to allow for the fact that that machine may not agree with you about
how ints are stored, so you’ll both need to talk to each other in network order, and
do your own conversions to/from your native host order as necessary…

简单总结就是任何要发到网络的整形数字都应转换成网络字节顺序再用,以及任何从网络接收的整形数字都应当用ntohs转换成本机适用的整形。