파일에서 10진수형태로 된 ip주소를 네트워크 바이트 형태로 변환하여 출력한다.
파일명 ipaddr.txt
파일 내용 ip_addr = 3550033200
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define NAME_SIZE 50
#define BUFSIZE 30
#define LINE_SIZE 256
#define LINE_BUF 10000
char *trimLeft(char *string);
void ip_convert(char *p);
int main(void)
{
char ip_addr[NAME_SIZE];
char ip_addr1[NAME_SIZE];
char *a;
memset(ip_addr,'\0',NAME_SIZE);
const char del_line[] = "=\t";
int size;
char *token;
char file_buf[LINE_BUF];
FILE *fp;
if((fp = fopen("ipaddr.txt","r")) == NULL)
{
printf("125 Can't read file\n");
exit(1);
}
while(!feof(fp))
{
memset(file_buf,'\0',LINE_BUF);
fgets(file_buf,LINE_BUF,fp);
if(strchr(file_buf,'#') == NULL)
{
if(strstr(file_buf,"ip_addr"))
{
strtok(file_buf,del_line);
token = strtok(NULL,del_line);
size = strlen(token);
strncpy(ip_addr,token,size);
strncpy(ip_addr,token,NAME_SIZE);
if(ip_addr[size-1] == '\n')
{
ip_addr[size-1] = '\0';
}
}
}
}
a = trimLeft(ip_addr);
ip_convert(a);
}
char *trimLeft(char *string)
{
while(*string)
{
if(isspace(*string))
{
++string;
}
else
{
break;
}
}
return string;
}
void ip_convert(char *p)
{
struct in_addr in;
unsigned long int ip;
sscanf(p "%lu",&ip);
in.s_addr = htonl(ip);
printf("%s\n",inet_ntoa(in));
}