百度空间 | 百度首页 
 
查看文章
 
iptoint && inttoip
2009-09-02 18:00
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>


static char const rcsid[] = "$Id: rv_iptoint.c,v 1.2 2004/03/10 18:04:33 wilhelm Exp $";

unsigned int rv_iptoint (char * ipstring) {
/* ==============

Converts an IP number (e.g. 1.2.3.4) into an 32 unsigned int ("0x01020304").

Input : char * ipstring String containing the ip number
Output: unsigned int IP number as a 32 bit unsigned int.

Non-numbers in the input string will be converted to FF.


$Author: wilhelm $
$Date: 2004/03/10 18:04:33 $
$Revision: 1.2 $

*/

unsigned int temp;
char buffer[10];
char *point= &buffer[0];
int i;

point = strtok ( ipstring, "." );
if (point == NULL) { return 0; }

if (strcmp(point, "??") == 0) {
temp = 0xFF;
}
else {
temp = (int) strtol (point, (char**)NULL, 10);
}

for (i=0 ; i<3 ; i++) {
point = strtok ( NULL, "." );
if ( (point == NULL) ) {
return 0;
}
else if ((strcmp(point, "??") == 0) ) {
temp = temp*0x100 + 0xFF;
}
else {
temp = temp*0x100 + (int) strtol (point, (char**)NULL, 10);
}
}

return temp;
}



#include <stdio.h>
#include <strings.h>

static char const rcsid[] = "$Id: rv_inttoip.c,v 1.1 2002/08/15 23:15:48 ttraffic Exp $";

char* rv_inttoip (unsigned int ipno, char* point) {
/* ============

Converts an unsigned int ("0x01020304") into a standard IP number (1.2.3.4);
Space for the string must have been alloced in the calling routine.

$Author: ttraffic $
$Date: 2002/08/15 23:15:48 $
$Revision: 1.1 $

*/
int byte[4], i;

for (i=0 ; i<4 ; i++) {
byte[i] = ipno & 0xFF;
ipno = ipno / 0x100;
}

sprintf (point, "%d.%d.%d.%d", byte[3], byte[2], byte[1], byte[0]);

return point;
}

类别:c语言实践 | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu