Okay, here is a C code implementation for email validation. It avoids third-party libraries and uses standard C functions (<string.h>, <ctype.h>). It focuses on common structural rules rather than the full complexity of RFC 5322.
This code is designed to be easily compiled into a shared/dynamic library.
1. Header File (email_validator.h)
#ifndef EMAIL_VALIDATOR_H
#define EMAIL_VALIDATOR_H
// Define EXPORT based on platform (for visibility in DLL/SO)
#if defined(_WIN32) || defined(__CYGWIN__)
#ifdef BUILDING_DLL
#ifdef __GNUC__
#define EXPORT __attribute__ ((dllexport))
#else
#define EXPORT __declspec(dllexport) // Note: actually gcc seems to also supports this syntax.
#endif
#else
#ifdef __GNUC__
#define EXPORT __attribute__ ((dllimport))
#else
#define EXPORT __declspec(dllimport) // Note: actually gcc seems to also supports this syntax.
#endif
#endif
#define LOCAL
#else
#if __GNUC__ >= 4
#define EXPORT __attribute__ ((visibility ("default")))
#define LOCAL __attribute__ ((visibility ("hidden")))
#else
#define EXPORT
#define LOCAL
#endif
#endif
/*
* Validates an email address string based on common structural rules.
*
* This validation is not fully RFC 5322 compliant but covers most common cases.
* It checks for:
* - Presence of exactly one '@' symbol.
* - Non-empty local part and domain part.
* - Valid characters in local part (alphanumeric, '.', '_', '+', '-').
* - Local part doesn't start or end with '.', no consecutive '..'.
* - Valid characters in domain part (alphanumeric, '.', '-').
* - Domain part contains at least one '.'.
* - Domain labels (parts between dots) don't start or end with '-'.
* - Top-Level Domain (TLD) has at least 2 alphabetic characters.
* - Reasonable overall length limits.
*
* Args:
* email: The null-terminated string containing the email address to validate.
*
* Returns:
* 1 if the email address is considered valid according to the rules.
* 0 if the email address is considered invalid or if the input is NULL.
*/
EXPORT int validate_email(const char *email);
#endif // EMAIL_VALIDATOR_H
2. Source File (email_validator.c)
#include "email_validator.h"
#include <string.h> // For strlen, strchr, strrchr
#include <ctype.h> // For isalnum, isalpha
#include <stddef.h> // For size_t
// Define maximum lengths (practical limits, not strict RFC)
#define MAX_EMAIL_LEN 256
#define MAX_LOCAL_PART_LEN 64
#define MAX_DOMAIN_PART_LEN 255
#define MIN_TLD_LEN 2
// Helper function to check if a character is valid for the local part
static int is_valid_local_char(char c) {
return isalnum(c) || c == '.' || c == '_' || c == '+' || c == '-';
}
// Helper function to check if a character is valid for a domain label
static int is_valid_domain_char(char c) {
return isalnum(c) || c == '-';
}
/*
* Implementation of the validation function.
* Marked as EXPORT for dynamic library visibility.
*/
EXPORT int validate_email(const char *email) {
if (email == NULL) {
return 0; // Invalid input
}
size_t total_len = strlen(email);
if (total_len == 0 || total_len > MAX_EMAIL_LEN) {
return 0; // Empty or too long
}
// --- Find exactly one '@' symbol ---
const char *at_sym = strchr(email, '@');
if (at_sym == NULL || at_sym != strrchr(email, '@')) {
return 0; // No '@' or more than one '@'
}
// --- Calculate part lengths ---
size_t local_len = at_sym - email;
size_t domain_len = total_len - local_len - 1; // -1 for '@'
// --- Validate Local Part ---
if (local_len == 0 || local_len > MAX_LOCAL_PART_LEN) {
return 0; // Empty or too long
}
// Check first and last char of local part
if (email[0] == '.' || email[local_len - 1] == '.') {
return 0; // Starts or ends with '.'
}
// Check characters and consecutive dots in local part
for (size_t i = 0; i < local_len; ++i) {
if (!is_valid_local_char(email[i])) {
return 0; // Invalid character
}
if (email[i] == '.' && i + 1 < local_len && email[i + 1] == '.') {
return 0; // Consecutive dots ".."
}
}
// --- Validate Domain Part ---
const char *domain_part = at_sym + 1;
if (domain_len == 0 || domain_len > MAX_DOMAIN_PART_LEN) {
return 0; // Empty or too long
}
// Domain must contain at least one dot
const char *last_dot = strrchr(domain_part, '.');
if (last_dot == NULL || last_dot == domain_part || last_dot == domain_part + domain_len - 1) {
// No dot, or dot is first/last char of domain part
return 0;
}
// Check TLD (part after the last dot)
size_t tld_len = domain_part + domain_len - (last_dot + 1);
if (tld_len < MIN_TLD_LEN) {
return 0; // TLD too short
}
for (size_t i = 0; i < tld_len; ++i) {
if (!isalpha(last_dot[1 + i])) {
return 0; // TLD must contain only letters (common simplification)
}
}
// Check domain characters and label structure
char prev_char = '@'; // Treat '@' as the start marker before the domain
for (size_t i = 0; i < domain_len; ++i) {
char current_char = domain_part[i];
if (current_char == '.') {
if (prev_char == '.' || prev_char == '-') {
return 0; // Consecutive dots "..", or "-." sequence
}
} else if (current_char == '-') {
if (prev_char == '.' || prev_char == '@') {
return 0; // Label starts with '-' (e.g., ". -" or "@-")
}
// Check next char - if it's '.' or end of string, invalid
if (i + 1 == domain_len || domain_part[i+1] == '.') {
return 0; // Label ends with '-' (e.g., "-." or "-$")
}
} else if (!isalnum(current_char)) {
return 0; // Invalid character in domain (only alnum, '.', '-' allowed)
}
// If we are here, current_char is valid in its context for now
prev_char = current_char;
}
// Final check: Domain cannot end with '-' (already checked for '.')
// This is covered by the loop check `domain_part[i+1] == '.'` when `i` is `domain_len - 1`
// If all checks passed
return 1;
}
Explanation:
-
Header (email_validator.h):
- Includes standard guards (
#ifndef/#define/#endif).
- Defines
EXPORT macro: This is crucial for dynamic libraries. It uses platform-specific attributes (__declspec(dllexport/dllimport) on Windows, __attribute__ ((visibility ("default"))) on GCC/Clang) to ensure the validate_email function is visible outside the compiled library. You'll need to define BUILDING_DLL when compiling the DLL itself on Windows.
- Declares the
validate_email function prototype with the EXPORT macro.
-
Source (email_validator.c):
- Includes the header and necessary standard C headers.
- Defines practical maximum lengths. Real RFC limits are complex and sometimes larger, but these prevent trivial overflows and align with common practices.
is_valid_local_char, is_valid_domain_char: Small helper functions for clarity.
validate_email Function:
- Handles
NULL input.
- Checks overall length.
- Uses
strchr and strrchr to find exactly one @.
- Calculates lengths of local and domain parts.
- Local Part Validation: Checks length, ensures it doesn't start/end with
., iterates through characters checking validity and for consecutive ...
- Domain Part Validation:
- Checks length.
- Uses
strrchr to find the last dot. Ensures it exists and isn't at the very beginning or end of the domain part.
- TLD Validation: Checks the part after the last dot. Ensures minimum length (
MIN_TLD_LEN) and that all characters are alphabetic (isalpha). This is a simplification; real TLDs can include numbers (rarely) or be IDNs (punycode).
- Domain Character/Label Validation: Iterates through the domain part.
- Checks for invalid characters (anything not alphanumeric, dot, or hyphen).
- Checks for invalid sequences like
.., .-, -..
- Checks that labels (parts between dots) don't start or end with a hyphen.
How to Compile into a Dynamic Library:
Linux/macOS (using GCC/Clang):
# Compile the C source file into an object file
gcc -fPIC -c email_validator.c -o email_validator.o
# Link the object file into a shared library (.so)
gcc -shared -o libemailvalidator.so email_validator.o
-fPIC: Generate Position Independent Code (required for shared libraries).
-shared: Create a shared library.
Windows (using GCC/MinGW):
# Compile the C source file into an object file, defining BUILDING_DLL
gcc -DBUILDING_DLL -c email_validator.c -o email_validator.o
# Link the object file into a DLL
gcc -shared -o emailvalidator.dll email_validator.o -Wl,--out-implib,libemailvalidator.a
-DBUILDING_DLL: Defines the macro used in the header to set EXPORT correctly for dllexport.
-shared: Create a shared library (DLL).
-Wl,--out-implib,libemailvalidator.a: Creates an import library (.a) which is often helpful when linking against the DLL later with GCC.
Windows (using MSVC - Microsoft Visual C++ Compiler):
# Compile and link in one step, defining BUILDING_DLL
cl /D_USRDLL /D_WINDLL /DBUILDING_DLL email_validator.c /link /DLL /OUT:emailvalidator.dll
/D_USRDLL /D_WINDLL: Standard defines for building a DLL.
/DBUILDING_DLL: Defines the macro for dllexport.
/DLL: Tells the linker to create a DLL.
/OUT:emailvalidator.dll: Specifies the output filename.
Remember to place the email_validator.h file where your application code (that will use the library) can find it, and ensure the compiled library (.so or .dll) is placed where the system's dynamic linker can find it at runtime (e.g., in the same directory as the executable, a standard system library path, or a path specified in LD_LIBRARY_PATH / PATH).