socket编程(一)

来源:互联网 发布:csol刀战优化 编辑:程序博客网 时间:2024/05/16 09:54

1.什么是socket?

(1)socket可以看成是用户进程与内核网络协议的编程接口。
(2)socket不仅可以用于本机的进程间通信,还可以用于网络不同主机的进程间通信。异构架构可以不同(手机<->PC)

2.IPV4套接口地址结构

IPV4套接口地址结构通常也称为“网际套接字地址结构”,它以sockaddr_in命名,定义在头文件<netinet/in.h>中
struct sockaddr_in {
    uint8_t sin_len;
    sa_family_t sin_family;(TCP/IP协议,或者Unix域协议)
    in_port_t sin_port;
     struct in_addr sin_addr;
    char sin_zero[8];
};

man 7 ip

3.网络字节序

字节序
(1)大端字节序
     最高有效位(MSB:Most Significant Bit)存储于最低内存地址处,最低有效位(LSB:Lowest Significant Bit)存储于最高内存地址处。
(2)小端字节序
     最高有效位(MSB:Most Significant Bit)存储于最高内存地址处,最低有效位(LSB:Lowest Significant Bit)存储于最低内存地址处。
主机字节序
     不同的主机有不同的字节序,如x86为小端字节序,Motorola 6800为大端字节序,ARM字节序是可配置的。
网络字节序

     网络字节序规定为大端字节序。

4.字节序转换函数

uint32_t htnol(uint32_t hostlong);
uint16_t htnos(uint16_t hostshort);
uint32_t ntnol(uint32_t netlong);
uint16_t ntnol(uint16_t netshort);
说明:h代表host;n代表network;s代表short;l代表long

#include <stdio.h>#include <arpa/inet.h>int main () {  unsigned int x = 0x12345678;  unsigned char* p = (unsigned char*)&x;  printf("%0x %0x %0x %0x\n", p[0], p[1], p[2], p[3]);    unsigned int y = htonl(x);  p = (unsigned char*)&y;  printf("%0x %0x %0x %0x\n", p[0], p[1], p[2], p[3]);  return 0;}

Output:

78 56 34 12
12 34 56 78



5.地址转换函数

#include <netinet/in.h>
#include <arpa/inet.h>

int inet_aton(const char* cp, struct in_addr* inp);
in_addr_t inet_addr(const char* cp);
char* inet_ntoa(struct in_addr in);

#include <stdio.h>#include <arpa/inet.h>int main () {  unsigned long addr = inet_addr("192.168.0.100");  printf("addr=%u\n", ntohl(addr));    struct in_addr ipaddr;  ipaddr.s_addr = addr;  printf("%s\n", inet_ntoa(ipaddr));  return 0;}


Output:

addr=3232235620
192.168.0.100

6.套接字类型

流式套接字(SOCK_STREAM)
提供面向连接的,可靠的数据传输服务,数据无差错,无重复的发送,且按发送顺序接收。
数据报式套接字(SOCK_DREAM)
提供无连接服务。不提供无措保证,数据可能丢失或重复,并且接收顺序混乱。
原始套接字(SOCK_RAW)