✅ 목표 (Goal)

입력받은 문자열이 IP 형식이 맞는지 검사해보자.

✅ 예제 (Example)

//C언어 IP 유효성 검사하기
//==== = > Source Code <=====

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
//#include <unistd.h> unix 헤더파일 fork, getuid, setuid 등
#include <stdlib.h>

bool ip_check(char* ip) {
	if (strcmp(ip, " ") == 0) {
		printf("IP address NULL!\\n");
		return false;
	}
	int len = strlen(ip);
	if (len > 15 || len < 7) { return false; }
	int nNumCount = 0;
	int nDotCount = 0;
	int i = 0;
	for (i = 0; i < len; i++) {
		if (ip[i] < '0' || ip[i] > '9') {
			if (ip[i] == '.') {
				++nDotCount;
				nNumCount = 0;
			}
			else {
				return false;
			}
		}
		else {
			if (++nNumCount > 3)
				return false;
		}
	}
	if (nDotCount != 3)
		return false;
	return true;
}

int main(int argc, char** argv[]) {
	char ip[15];
	printf("input ip address.\\n");
	printf("example #1: 192.168.1.1\\n");
	printf("ip : ");
	scanf("%s", &ip);
	printf("Your press ip : %s\\n", &ip); 
	if (ip_check(ip) == false) {
		printf("ip is not valild\\n");
	}
	else {
		printf("ip is valild\\n");
	}
	exit(0);
}

//출처: <https://kleeck.tistory.com/entry/C언어-IP-유효성-검사하기-2> [암흑도깨비 새로운 도전:티스토리]

image.png

image.png

✅ 참조 (Ref.)

▼ [C언어] IP 유효성 검사하기

https://kleeck.tistory.com/entry/C언어-IP-유효성-검사하기-2

▼ 자기 자신 IP Address C 코드로 확인하기.(SIOCGIFADDR)

https://technote.kr/176#google_vignette

▼ C언어 NIC IP 확인 소스 코드