MAC文本格式地址to网络字节序

#include    <sys/types.h>
#include    <netinet/in.h>
#include    <stdio.h>
 
/* 
 * Check whether "cp" is a valid ascii representation
 * of an MAC address and convert to a binary address.
 * Returns 1 if the address is valid, 0 if not.
 */
int inet_mton(const char *cp, u_char *ap)
{
	int colons = 0;
        quad_t acc = 0, addr = 0;
  
      do {
      register char cc = *cp;
  
      switch (cc) {
      case '0':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
          acc = acc * 16 + (cc - '0');
          break;
  
      case 'a':
      case 'b':
      case 'c':
      case 'd':
      case 'e':
      case 'f':
          acc = acc * 16 + (cc - 'a' + 10);
          break;
  
      case 'A':
      case 'B':
      case 'C':
      case 'D':
      case 'E':
      case 'F':
          acc = acc * 16 + (cc - 'A' + 10);
          break;
  
      case ':':
          if (++colons > 5) {
          return 0;
          }
          /* Fall down to case '\0' */
  
      case '\0':
          if (acc > 0xFF) {
          return 0;
          }
          addr = addr << 8 | acc;
          acc = 0;
          break;
  
      default:
          return 0;
      }
      } while (*cp++) ;
  
      /* Normalize the address */
      if (colons < 5) {
      addr <<= 8 * (5 - colons) ;
      }
  
      /* Store it if requested */
      if (ap) {
      /* Convert address to network bytes order(big-endian) */
      #if __BYTE_ORDER == __LITTLE_ENDIAN 
      int i = 0, j = 0;
      for(i=0,j=5; i<6,j>=0; i++,j--){
          ap[i] = ((u_char *) &addr)[j];
      }
      #elif __BYTE_ORDER == __BIG_ENDIAN
      ap = (u_char *) &addr;
      #endif
      }
  
      return 1;
}

int main()
{ /* test inet_mton(const char *cp, u_char *ap) */         
    char *macaddr = "00:06:1B:D1:73:1F";
     u_char m_addr[6];
 
    printf("%s\n", macaddr);
    if(inet_mton(macaddr, m_addr)){
       int i = 0;
        for(i=0; i<6; i++){
            printf("%2x:", m_addr[i]);
        }
    }

     return 0;
}
 

你可能感兴趣的:(C++,c,C#,F#,J#)