Linux函数--inet_pton / inet_ntop
生活随笔
收集整理的這篇文章主要介紹了
Linux函数--inet_pton / inet_ntop
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
http://blog.csdn.net/lindyl/article/details/10427925
inet_pton?和 inet_ntop
Linux下這2個IP地址轉(zhuǎn)換函數(shù),可以在將IP地址在“點分十進制”和“整數(shù)”之間轉(zhuǎn)換而且,inet_pton和inet_ntop這2個函數(shù)能夠處理ipv4和ipv6。算是比較新的函數(shù)了。
inet_pton
函數(shù)原型如下[將"點分十進制" -> "整數(shù)"]?
#include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> int inet_pton(int af, const char *src, void *dst); //這個函數(shù)轉(zhuǎn)換字符串到網(wǎng)絡地址,第一個參數(shù)af是地址族,轉(zhuǎn)換后存在dst中 inet_pton是inet_addr的擴展,支持的多地址族有下列:
af = AF_INET
src為指向字符型的地址,即ASCII的地址的首地址(ddd.ddd.ddd.ddd格式的),函數(shù)將該地址轉(zhuǎn)換為in_addr的結構體,并復制在*dst中
af = AF_INET6
src為指向IPV6的地址,函數(shù)將該地址轉(zhuǎn)換為in6_addr的結構體,并復制在*dst中。如果函數(shù)出錯將返回一個負值,并將errno設置為EAFNOSUPPORT,如果參數(shù)af指定的地址族和src格式不對,函數(shù)將返回0。
inet_ntop
函數(shù)原型如下[將"點分十進制" -> "整數(shù)"]
#include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt); //這個函數(shù)轉(zhuǎn)換網(wǎng)絡二進制結構到ASCII類型的地址,參數(shù)的作用和上面相同,只是多了一個參數(shù)socklen_t cnt, //他是所指向緩存區(qū)dst的大小,避免溢出,如果緩存區(qū)太小無法存儲地址的值,則返回一個空指針,并將errno置為ENOSPC?
編程實例:
#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地址結構體// 輸入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); }總結
以上是生活随笔為你收集整理的Linux函数--inet_pton / inet_ntop的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 防火墙5788剧情介绍
- 下一篇: linux socket 编程(C语言)