在設計網路連線的程式裡面, 常常會需要輸入ip或是host name. 設計良好的程式應該是要能接受這兩種不同的格式, 然後自行轉換.
下面就介紹如何轉換ip到host name以及host name到ip.
//----------------------
// Declare and initialize variables
hostent* remoteHost;
char* host_name;
unsigned int addr;
//----------------------
// User inputs name of host
printf("Input name of host: ");
host_name = (char*) malloc(sizeof(char*)*16);
fgets(host_name, 16, stdin);
// If the user input is an alpha name for the host, use gethostbyname()
// If not, get host by addr (assume IPv4)
if (isalpha(host_name[0])) { /* host address is a name */
host_name[strlen(host_name)-1] = '\0'; /* NULL TERMINATED */
remoteHost = gethostbyname(host_name);
}
else {
addr = inet_addr(host_name);
remoteHost = gethostbyaddr((char *) &addr, 4, AF_INET);
}
上面的程式碼主要功能在於輸入host name轉成ip, 或是輸入ip轉成host name.
if (isalpha(host_name[0])) { /* host address is a name */
host_name[strlen(host_name)-1] = '\0'; /* NULL TERMINATED */
remoteHost = gethostbyname(host_name);
}
這一段是先判斷輸入的內容是否有英文字母, 如果是英文字母則判斷為host name.
下面就用gethostbyname進行轉換.
else {
addr = inet_addr(host_name);
remoteHost = gethostbyaddr((char *) &addr, 4, AF_INET);
}
而這一段是判斷為ip address, 先將ip address用inet_addr轉成internal address形式,
再用gethostbyaddr取得host資訊.
取得host資訊以後, 再以remoteHost->h_name取得host name或是ip address.
如此一來就能在使用者輸入ip或是host name時同時取得兩種資訊.
參考資料 :
MSDN