用strtok()来解析形如192.168.0.115:3333的IP地址。实现这个功能有两个关键点,一是对strtok()的正确使用,二是格式的转换。
#include
#include
#include
#define IP_SZ 20
struct IPAddr {
unsigned char ip[4];
unsigned short port;
};
/*对形如192.168.0.115:3333的地址,先用":",把地址分割成两段,
再用"."逐个分割。*/
int parserIP(const char* ip_str, struct IPAddr* aIPAddr) {
char *bufIP, *bufPort, *bufIP0, *bufIP1, *bufIP2, *bufIP3;
bufIP = strtok(ip_str, ":");
bufPort = strtok(NULL, ":");
bufIP0 = strtok(bufIP, ".");
bufIP1 = strtok(NULL, ".");
bufIP2 = strtok(NULL, ".");
bufIP3 = strtok(NULL, ".");
aIPAddr->ip[0] = (unsigned char)atoi(bufIP0);
aIPAddr->ip[1] = (unsigned char)atoi(bufIP1);
aIPAddr->ip[2] = (unsigned char)atoi(bufIP2);
aIPAddr->ip[3] = (unsigned char)atoi(bufIP3);
aIPAddr->port = atoi(bufPort);
return 0;
}
/*改进的fgets(),删除末尾的'\n'*/
void Fgets(char *s, int n, FILE * stream) {
fgets(s, n, stream);
int len = strlen(s);
s[len] = '\0';
}
int main()
{
struct IPAddr IPAd;
char buf[IP_SZ];
printf("input a IP address, like 192.168.0.112:2222\n");
Fgets(buf, IP_SZ, stdin);
printf("get a IP address:%s\n", buf);
parserIP(buf, &IPAd);
printf("after parsering, the IP is:\n");
printf(" IPAd->ip[0]=%u\n IPAd->ip[1]=%u\n IPAd->ip[2]=%u\n IPAd->ip[3]=%u\n IPAd->port=%u\n",
IPAd.ip[0], IPAd.ip[1], IPAd.ip[2], IPAd.ip[3], IPAd.port);
return 0;
}
某次的运行结果为: