Last active
December 16, 2015 06:28
-
-
Save RonjaPonja/5391315 to your computer and use it in GitHub Desktop.
Just a quick reference of how to work with IPs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
enum { | |
/* Maximum length of a string representing an IPv4 address */ | |
IP4_LEN_MAX = 3 * 4 + 3 + 1 | |
}; | |
int | |
main(void) { | |
// Input IPs in text format | |
char *startIP = (char *) "192.168.178.2"; | |
char *stopIP = (char *) "192.168.178.1"; | |
printf("start=%s stop=%s\n\n", startIP, stopIP); | |
// Convet text to binary format | |
uint32_t start, stop; | |
inet_pton(AF_INET, startIP, &start); | |
inet_pton(AF_INET, stopIP, &stop); | |
printf("start=0x%08X stop=0x%08X\n", start, stop); | |
// Convert number from network-byte-order (big endian) | |
// to host-byte-order (little endian for x86) | |
start = ntohl(start); | |
stop = ntohl(stop); | |
printf("start=0x%08X stop=0x%08X\n", start, stop); | |
if (start > stop) { int temp = start; start = stop; stop = temp; } | |
// Convert number from host-byte-order (little endian for x86) | |
// to network-byte-order (big endian) | |
start = ntohl(start); | |
stop = ntohl(stop); | |
printf("start=0x%08X 0stop=0x%08X\n\n", start, stop); | |
/* Four octets, at most 3 bytes + 3 bytes as delimiters + 1 terminating 0x00 */ | |
startIP =(char *) calloc(IP4_LEN_MAX, sizeof(char)); | |
stopIP =(char *) calloc(IP4_LEN_MAX, sizeof(char)); | |
// Convet binary to text format | |
inet_ntop(AF_INET, &start, startIP, IP4_LEN_MAX * sizeof(*startIP)); | |
inet_ntop(AF_INET, &stop, stopIP, IP4_LEN_MAX * sizeof(*startIP)); | |
printf("start=%s stop=%s\n", startIP, stopIP); | |
free(startIP); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment