原文地址:http://blog.sina.com.cn/s/blog_6151984a0100etj1.html
sockaddr结构体
sockaddr的缺陷:sa_data把目标地址和端口信息混在一起了
struct sockaddr { unsigned short sa_family; char sa_data[14]; }; |
sa_family是通信类型,最常用的值是 "AF_INET" sa_data14字节,包含套接字中的目标地址和端口信息 |
struct sockaddr_in { short int sin_family; unsigned short int sin_port; struct in_addr sin_addr;
unsigned char sin_zero[8]; } |
struct sockaddr_in cliaddr; bzero(&cliaddr,sizeof(cliaddr)); |
struct sockaddr_in ina; bzero(&ina,sizeof(ina)); ina.sin_family=AF_INET; ina.sin_port=htons(23); ina.sin_addr.s_addr = inet_addr("132.241.5.10"); |
最典型的源、目的节点socket定义
对于源、目的地址和源、目的地址端口,需要建立两个socket变量
cliaddr绑定源地址和源端口
servaddr用于connect和sendto的设定目的地址和目的端口
struct sockaddr_in servaddr,cliaddr; create_socket(char *server_addr_string,unsigned int server_port) { 源socket赋值 bzero(&cliaddr,sizeof(cliaddr)); cliaddr.sin_family = AF_INET; 通常TCP/UDP 协议源地址和端口都是随机的 cliaddr.sin_addr.s_addr = htons(INADDR_ANY); cliaddr.sin_port = htons(0); 目的socket赋值 bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; inet_aton(server_addr_string,&servaddr.sin_addr); servaddr.sin_port = htons(server_port); } |
inet_aton(server_addr_string,&myaddr.sin_addr); |
myaddr.sin_addr.s_addr = inet_addr("132.241.5.10"); |
INADDR_ANY转不转NBO随便 myaddr.sin_addr.s_addr = htons(INADDR_ANY); myaddr.sin_addr.s_addr = INADDR_ANY; |
#define MYPORT 3490 myaddr.sin_port = htons(MYPORT); |
0(随机端口)转不转NBO随便 myaddr.sin_port = htons(0); myaddr.sin_port = 0; |
struct sockaddr_in ina; ina.sin_addr.s_addr = inet_addr("132.241.5.10"); |
struct sockaddr_in ina; inet_aton("132.241.5.10",&ina.sin_addr); |
a1 = inet_ntoa(ina.sin_addr); printf("address 1: %s\n",a1); |
address 1: 132.241.5.10 |