设为首页 加入收藏

TOP

IPv4 IPv6 Socket 编程相关结构
2014-11-24 12:00:25 来源: 作者: 【 】 浏览:0
Tags:IPv4 IPv6 Socket 编程 相关 结构

Structures for handling internet addresses


These are the basic structures for all syscalls and functions that deal with internet addresses. Often you'll usegetaddinfo() to fill these structures out, and then will read them when you have to.


In memory, the struct sockaddr_in and struct sockaddr_in6 share the same beginning structure as struct sockaddr , and you can freely cast the pointer of one type to the other without any harm, except the possible end of the universe.


Just kidding on that end-of-the-universe thing...if the universe does end when you cast a struct sockaddr_in* to a struct sockaddr* , I promise you it's pure coincidence and you shouldn't even worry about it.


So, with that in mind, remember that whenever a function says it takes a struct sockaddr* you can cast your struct sockaddr_in* , struct sockaddr_in6* , or struct sockadd_storage* to that type with ease and safety.


struct sockaddr_in is the structure used with IPv4 addresses (e.g. "192.0.2.10"). It holds an address family (AF_INET), a port insin_port, and an IPv4 address insin_addr.


There's also this sin_zero field in struct sockaddr_in which some people claim must be set to zero. Other people don't claim anything about it (the Linux documentation doesn't even mention it at all), and setting it to zero doesn't seem to be actually necessary. So, if you feel like it, set it to zero usingmemset().


Now, that struct in_addr is a weird beast on different systems. Sometimes it's a crazyunion with all kinds of#defines and other nonsense. But what you should do is only use thes_addr field in this structure, because many systems only implement that one.


struct sockadd_in6 and struct in6_addr are very similar, except they're used for IPv6.


struct sockaddr_storage is a struct you can pass toaccept() orrecvfrom() when you're trying to write IP version-agnostic code and you don't know if the new address is going to be IPv4 or IPv6. The struct sockaddr_storage structure is large enough to hold both types, unlike the original small struct sockaddr .


Description


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Linux Administration Handbook .. 下一篇建立ARM Linux GCC交叉编译环境

评论

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

·Asus Armoury Crate (2025-12-26 02:52:33)
·WindowsFX (LinuxFX) (2025-12-26 02:52:30)
·[ Linux运维学习 ] (2025-12-26 02:52:27)
·HTTPS 详解一:附带 (2025-12-26 02:20:37)
·TCP/IP协议到底在讲 (2025-12-26 02:20:34)