ÔÚϵͳ±à³ÌµÄsocketÄ£¿éÖУ¬ÔÚ²»Í¬»úÆ÷Ö®¼äµÄ½ø³ÌͨÐÅ£¬¼´ÍøÂçͨÐÅ£¬ÒªÍ¨¹ýsocketÌ×½Ó×ÖÒÔ¼°Ïà¹ØµÄº¯Êý£¨send/sendto£¬recv/recvfromµÈ£©À´ÊµÏÖ£¬µ«ÕâÀïÓÐÒ»¸öºÜÖØÒªµÄÌõ¼þ£¬ÔÚͨÐź¯ÊýʵÏÖÇ°£¬ÒªÏÈÈ·¶¨ÄãµÄͨÐŶÔÏ󣨷þÎñÆ÷»òÕßÁíÍâÒ»¸ö¿Í»§¶ËµÈ£©£¬ËùÒÔÕâÀï¾ÍÉæ¼°µ½Ò»¸ö¶¯×÷£¬°ÑͨÐŶÔÏóµÄÏà¹ØÐÅÏ¢ÉèÖúÃÔÙͨÐÅ¡£¶øÕâÏà¹ØµÄÐÅÏ¢°üÀ¨Í¨ÐŶÔÏóµÄipµØÖ·ºÍ¶Ë¿ÚºÅµÈ£¬ipµØÖ·ºÍ¶Ë¿ÚºÅÓÈΪÖØÒª¡£Òò´ËÒª°ÑͨÐŶÔÏóµÄipµØÖ·ºÍ¶Ë¿ÚºÅʵÏÖÔÚÒ»¸ö½á¹¹ÌåÖУ¬ÔÚͨÐź¯ÊýÖд«µÝÕâ¸ö½á¹¹Ìå¡£
struct sockaddr
{
unsigned short sa_family; /*µØÖ·×å*/
char sa_data[14]; /*14 ×Ö½ÚµÄÐÒéµØÖ·£¬°üº¬¸Ã socket µÄ IP µØÖ·ºÍ¶Ë¿ÚºÅ¡£ */
};
struct sockaddr_in
{
short int sin_family; /*µØÖ·×å*/
unsigned short int sin_port; /*¶Ë¿ÚºÅ*/
struct in_addr sin_addr; /*IP µØÖ·*/
unsigned char sin_zero[8]; /*Ìî³ä 0 ÒÔ±£³ÖÓë struct sockaddr ͬÑù´óС*/
};
struct in_addr
{
unsigned long int s_addr; /* 32 λ IPv4 µØÖ·£¬ÍøÂç×Ö½ÚÐò */
};
ÔÚÌî³äÕâ¸ö½á¹¹ÌåÇ°»¹ÓÐÒ»¸öÊÂÇéҪעÒâµÄ£¬¶Ë¿ÚºÅºÍipµØÖ·ÒªÒÔÍøÂç×Ö½ÚÐòµÄ·½Ê½´«µÝ£¬Òò´Ë²Ù×÷ϵͳÌṩÁ˽á¹ûת»»º¯ÊýÈ磺
¶Ë¿ÚµÄÖ÷»ú×Ö½ÚÐòÓëÍøÂç×Ö½ÚÐòµÄÏ໥ת»»
uint16_t htons(uint16_t hostshort)
uint16_t ntohs(uint16_t netshort)
ipµÄÖ÷»ú×Ö½ÚÐòÓëÍøÂç×Ö½ÚÐòµÄÏ໥ת»»
uint32_t ntohl(uint32_t netlong)
uint32_t htonl(uint32_t hostlong)
´ËÍ⻹ÓÐÒ»¸öµØ·½Ò²ÊÇÖØÒªÌõ¼þ£¬ipµØÖ·Òª´Óµã·ÖÊ®½øÖÆ£¨xxx.xxx.xxx.xxx£©×ª»»Îª32λÕûÐεĶþ½øÖÆÖµ²ÅÄܽø³ÌͨÐÅ£¬Òò´ËÓÐÏÂÃæÁ½¸öת»»º¯Êý£º
int inet_pton(int af, const char *src, void *dst); //µã·ÖÊ®½øÖÆת32λ¶þ½øÖÆ
const char *inet_ntop(int af, const void *src,char *dst, socklen_t size);
ʵÏÖÁËÇ°ÃæµÄ¼¸¸öº¯Êýºó£¬¾Í¿ÉÒÔ°ÑÏà¹ØµÄ½á¹ûÌîдµ½Ç°ÃæµÄ½á¹¹Ìå³ÉÔ±ÖÐ:
//Ä¿±ê(·þÎñÆ÷)µÄÏà¹ØÐÅÏ¢
struct sockaddr_in ser_addr ;
ser_addr.sin_family = AF_INET;//ÐÒéÀàÐÍ ipv4
ser_addr.sin_port = htons(1234);//·þÎñÆ÷¶Ë¿ÚºÅ--תΪÍøÂç×Ö½ÚÐò
//win·þÎñÆ÷ipµØÖ·
char src_ip[]="xxx.xxx.xxx.xxx";
//½«·þÎñÆ÷µÄipµØÖ·µã·ÖÊ®½øÖÆת»»Îª32λÕûÐ͵ÄÍø¿©×Ö½ÚÐò
ret = inet_pton(AF_INET,src_ip ,&i_ip);
//Ìî³äipµØÖ·µ½Ç°ÃæµÄ·þÎñÆ÷ÐÅÏ¢½á¹¹ÌåÖÐ
ser_addr.sin_addr.s_addr = i_ip;
//´´½¨Ì×½Ó×Ö ipv4 udpÐÒé
cli_socket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
//Çó³ö·þÎñÆ÷ÐÅÏ¢½á¹¹ÌåµÄ³¤¶È
socklen_t addr_len = sizeof(ser_addr);
char senbuf[]="this is client buf";
//·¢ËÍÐÅÏ¢¸ø·þÎñÆ÷
ssize_t senret = sendto(cli_socket,senbuf,strlen(senbuf),0,(struct sockaddr *)&ser_addr,addr_len);
¡¡
°´ÕÕÇ°ÃæµÄ˵·¨,ÉÏÃæµÄ³ÌÐòÓ¦¸Ã½«ipת»»ÎªÍøÂç×Ö½ÚÐòµÄ£º
¡¡
ret = inet_pton(AF_INET,src_ip ,&i_ip);
n_ip = htonl(i_ip) ;
ser_addr.sin_addr.s_addr = i_ip;
¡¡
½á¹ûÎÞ·¨ÁªÍ¨£¬µ«È¥µôn_ip = htonl(i_ip) ºó¼´¿ÉÒÔͨÐÅ£¬ÎªÊ²Ã´ÄØ£¿
ÒòΪûÓÐ×¢Ò⵽ǰ±ßinet_ptonºÍinet_ntopµÄ¾ßÌåÓ÷¨£¬Êµ¼ÊÉϵ÷ÓÃÕâÁ½¸öº¯Êýʱ¾ÍÒѾʵÏÖÁËipµØÖ·µÄÍøÂç×Ö½ÚÐòºÍÖ÷»ú×Ö½ÚÐòÒÔ¼°µã·ÖÊ®½øÖÆÓë32λÕûÐζþ½øÖƵÄÊý¾ÝÐÎʽµÄת»»ÁË£¬Òò´ËÔÚÌî³äÇ°±ß½á¹¹Ìå³ÉԱǰִÐе÷ÓÃinet_pton¶Ôip½øÐÐת»»¼´¿É£¬ÈçͬÉÏÃæ´úÂë¶ÎËùʾ¡£