C++中inet_pton、inet_ntop函數(shù)的用法
更新時間:2023年08月24日 14:28:10 作者:Lei Gong
這篇文章主要介紹了C++中inet_pton、inet_ntop函數(shù)的用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
C++中inet_pton、inet_ntop函數(shù)
頭文件
windows下:
#include <WS2tcpip.h>
linux下:
#include <sys/socket.h> #include <netinet/in.h> #include<arpa/inet.h>
inet_pton函數(shù)
將點分十進制串轉(zhuǎn)換成網(wǎng)絡(luò)字節(jié)序二進制值,此函數(shù)對IPv4地址和IPv6地址都能處理。
- 第一個參數(shù)可以是AF_INET或AF_INET6:
- 第二個參數(shù)是一個指向點分十進制串的指針:
- 第三個參數(shù)是一個指向轉(zhuǎn)換后的網(wǎng)絡(luò)字節(jié)序的二進制值的指針。
inet_ntop函數(shù)
和inet_pton函數(shù)正好相反,inet_ntop函數(shù)是將網(wǎng)絡(luò)字節(jié)序二進制值轉(zhuǎn)換成點分十進制串。
- 第一個參數(shù)可以是AF_INET或AF_INET6:
- 第二個參數(shù)是一個指向網(wǎng)絡(luò)字節(jié)序的二進制值的指針;
- 第三個參數(shù)是一個指向轉(zhuǎn)換后的點分十進制串的指針;
- 第四個參數(shù)是目標的大小,以免函數(shù)溢出其調(diào)用者的緩沖區(qū)。
樣例:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> int main (void) { char IPdotdec[20]; //存放點分十進制IP地址 struct in_addr s; // IPv4地址結(jié)構(gòu)體 // 輸入IP地址 printf("Please input IP address: "); scanf("%s", IPdotdec); // 轉(zhuǎn)換 inet_pton(AF_INET, IPdotdec, (void *)&s); printf("inet_pton: 0x%x\n", s.s_addr); // 注意得到的字節(jié)序 // 反轉(zhuǎn)換 inet_ntop(AF_INET, (void *)&s, IPdotdec, 16); printf("inet_ntop: %s\n", IPdotdec); }
inet_pton和inet_ntop使用總結(jié)
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main (void) { char IPdotdec[20]; //存放點分十進制IP地址 struct in_addr s; // IPv4地址結(jié)構(gòu)體 // 輸入IP地址 printf("Please input IP address: "); scanf("%s", IPdotdec); // 轉(zhuǎn)換 inet_pton(AF_INET, IPdotdec, (void *)&s); printf("inet_pton: 0x%x\n", s.s_addr); // 注意得到的字節(jié)序 // 反轉(zhuǎn)換 inet_ntop(AF_INET, (void *)&s, IPdotdec, 16); printf("inet_ntop: %s\n", IPdotdec); return 0; }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C語言中關(guān)于庫函數(shù) qsort 的模擬實現(xiàn)過程
庫函數(shù)的模擬實現(xiàn)有利于我們?nèi)ド钊肓私膺@個函數(shù)內(nèi)部是怎樣實現(xiàn)的,以及學習它的算法,使我們更加了解這個函數(shù)該怎樣去使用,接下來我將詳細的介紹qsort的應(yīng)用及用法,并且用代碼模擬實現(xiàn)它們的功能2021-09-09Visual?Studio2022下Opencv的配置圖文教程
本文主要介紹了Visual?Studio2022下Opencv的配置圖文教程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07